我正在尝试简化客户端应用程序中的错误处理,该应用程序使用JsonServiceClient
.
我在服务器上抛出的自定义异常在ResponseStatus
对象中被序列化,我可以看到 aWebServiceException
被抛出。
但目前我必须通过将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
- 我不打算在异常上扩展其他属性,它最终是为了方便,不必
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 状态代码。
然后 theThrowWebServiceException<TResponse>
和HandleResponseError<TResponse>
insideJsonServiceClient
可以在 map 中查找ErrorCode
up ,如果匹配,则返回该类型的新异常,将 theWebServiceException
作为参数传递,或者转换属性。
但最终目标是抛出一个更有用的错误。如果没有匹配,继续并继续抛出WebServiceException
.
我会覆盖ThrowWebServiceException<TResponse>
,HandleResponseError<TResponse>
但我认为这是不可能的。而且我不想构建自己的版本来提供此功能。
我希望我已经解释过了。