-
Notifications
You must be signed in to change notification settings - Fork 21
HandleResponse
MiNG edited this page May 3, 2018
·
2 revisions
SDK 中所有有返回内容的调用均统一返回 IResponse<XxxResult>
作为包装。
返回结果通过 IResponse<T>.Result
获取,错误信息通过 IResponse.Error
获取。
在业务响应了不成功的状态时 IResponse<T>.Result
将会返回 null
,为了确保后续操作的安全性,此时需要先确保返回的响应是成功的。
public static TResult HandleResponse<TResult>(IResponse<TResult> response)
where TResult : class
{
return response
// 此方法会确保返回的响应失败时候抛出 `LogServiceException`。
.EnsureSuccess();
// 此处获取Result是安全的。
.Result;
}
请求如果返回了不成功的状态时,可以从 IResponse.Error
或者 SDK 中抛出的 LogServiceException
中获取到错误信息。
public static void PrintError(IResponse response)
{
if (!response.IsSuccess)
{
Console.WriteLine($"RequestId (请求ID): {response.RequestId}");
Console.WriteLine($"ErrorCode (错误码): {response.Error.ErrorCode}");
Console.WriteLine($"ErrorMessage (错误消息): {response.Error.ErrorMessage}");
}
}
public static void PrintError(LogServiceException exception)
{
if (!response.IsSuccess)
{
Console.WriteLine($"RequestId (请求ID): {exception.RequestId}");
Console.WriteLine($"ErrorCode (错误码): {exception.ErrorCode}");
Console.WriteLine($"ErrorMessage (错误消息): {exception.ErrorMessage}");
}
}
SDK 中定义了 ErrorCode
类型用于提供已知的错误码,但其本质就是普通的字符串,可以与字符串相互进行转换。
其中,ErrorCode
可以进行如下操作:
public static void HandleError(Error error)
{
var errorCode = error.ErrorCode; // 假设错误码是 "SignatureNotMatch"。
Console.WriteLine($"Error={errorCode}"); // 输出 "Error=SignatureNotMatch" 。
// 与预定义的错误码进行比较。
if (errorCode == ErrorCode.SignatureNotMatch)
{
// ......
}
// 与自定义的错误码进行比较。
if (errorCode == "Foo")
{
// ......
}
// 可以使用 switch 语句,但 case 只能是常量值,所以可以用字面值相同的字符串代替。
switch (errorCode)
{
case "SignatureNotMatch":
{
// ......
break;
}
case "Foo":
{
// ......
break;
}
default:
{
// ......
break;
}
}
}
更多错误码的使用场景见:ErrorCodeTests