【发布时间】:2013-11-08 07:10:09
【问题描述】:
我正在尝试简化客户端应用程序中的错误处理,该应用程序使用 JsonServiceClient 使用 ServiceStack REST 服务。
我在服务器上抛出的自定义异常在ResponseStatus 对象中序列化,我可以看到WebServiceException 被抛出。
但目前我必须通过将WebServiceException ErrorCode 与我的异常类的类型名称匹配来检查我的异常类型。 (在共享 DTO 类中公开):
/** Current Method **/
try {
client.Get(new RequestThatWillFail());
} catch(WebServiceException ex) {
if(ex.ErrorCode == typeof(ValidationFailedException).Name)
Console.WriteLine("Validation error");
else if(ex.ErrorCode == typeof(UnauthorizedException).Name)
Console.WriteLine("Not logged in");
else if(ex.ErrorCode == typeof(ForbiddenException).Name)
Console.WriteLine("You're not allowed to do that!");
else
throw; // Unexpected exception
}
理想情况下,我希望JsonServiceClient 包含一些帮助方法或可覆盖的转换函数,使我能够将WebServiceException 转换为我已知的异常类型;这样我就可以以更传统的方式使用我的try ... catch:
/** Ideal Method **/
try {
client.Get(new RequestThatWillFail());
} catch(ValidationFailedException ex) { // (WebServiceException is converted)
Console.WriteLine("Validation error");
} catch(UnauthorizedException ex) {
Console.WriteLine("Not logged in");
} catch(ForbiddenException ex) {
Console.WriteLine("You're not allowed to do that!");
}
更新(澄清)
- 我有异常工作,我可以调试,并获得我需要的所有信息。
- 但我希望最终能够捕获我自己的异常,而不是通用的 WebServiceException
- 我不希望在异常上扩展其他属性,它最终是为了方便,不必在 catch 中执行大量
typeof(MyException).Name == ex.ErrorCode。
我希望能够向JsonServiceClient 提供以下地图:
{ Type typeof(Exception), string ErrorCode }
即类似的东西
JsonServiceClient.MapExceptionToErrorCode = {
{ typeof(BadRequestException), "BadRequestException" },
{ typeof(ValidationFailedException), "ValidationFailedException" },
{ typeof(UnauthorizedException), "UnauthorizedException" },
{ typeof(AnotherException), "AnotherException" }
// ...
}
类似于服务器当前如何将异常映射到 Http 状态代码。
然后JsonServiceClient 中的ThrowWebServiceException<TResponse> 和HandleResponseError<TResponse> 可以在映射中查找ErrorCode,如果匹配,则返回该类型的新异常,将WebServiceException 作为参数传递,或者翻译属性。
但最终目标是抛出一个更有用的错误。如果没有匹配,继续并继续抛出WebServiceException。
我会覆盖ThrowWebServiceException<TResponse> 和HandleResponseError<TResponse>,但我认为这是不可能的。而且我不想构建自己的版本来提供此功能。
我希望我已经解释过了。
【问题讨论】:
-
如果您将服务调用包装在客户端中,按照我的回答处理 WebServiceException,检查 ResponseStatus 错误并重新抛出您的异常,这是一种解决方法吗?
-
@stefan2410 如此有效地围绕
JsonServiceClient编写一个包装器,隐藏捕获WebServiceException 并将其作为我的类型重新抛出?我明白您在说什么,这可能是一种方法-尽管我担心使用包装器将其绑定到 ServiceClient,任何更改都可能会中断。也许是时候自负失败了。 ServiceStack v4 即将推出,因为它将是商业的,这也许是我可以建议的。我只是想找点东西让我的代码更整洁,这并不重要,毕竟它是有效的。
标签: c# exception-handling servicestack