3

我正在尝试简化客户端应用程序中的错误处理,该应用程序使用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 中查找ErrorCodeup ,如果匹配,则返回该类型的新异常,将 theWebServiceException作为参数传递,或者转换属性。

但最终目标是抛出一个更有用的错误。如果没有匹配,继续并继续抛出WebServiceException.

我会覆盖ThrowWebServiceException<TResponse>HandleResponseError<TResponse>但我认为这是不可能的。而且我不想构建自己的版本来提供此功能。

我希望我已经解释过了。

4

1 回答 1

3

我的异常处理方法是在服务端执行结构化错误处理覆盖默认异常处理
中描述的操作 我使用我的 ServiceRunner 并覆盖 HandleException。如果我的 API 异常被抛出,那么我创建一个自定义响应。

       public override object HandleException(IRequestContext requestContext,T request, 
                                                   Exception ex)
    {
         APIException apiex = ex as APIException;    // custo application exception
        if (apiex != null)
        {
            ResponseStatus rs = new ResponseStatus("APIException", apiex.message);
            rs.Errors = new List<ResponseError>();
            rs.Errors.Add(new ResponseError());
            rs.Errors[0].ErrorCode = apiex.errorCode.ToString();               
            rs.Errors[0].FieldName = requestContext.PathInfo;

             rs.Errors[1].ErrorCode = apiex.detailCode.ToString(); 
            // create an ErrorResponse with the ResponseStatus as parameter
            var errorResponse = DtoUtils.CreateErrorResponse(request, ex, rs);

            Log.Error("your_message", ex);   // log only the the error
            return errorResponse;

        }
        else
            return base.HandleException(requestContext, request, ex);

    }

更新: 在客户端,我为服务调用创建了一个包装器,在 WebServiceException 中,我检查了 ResponseStatus.Errors。如果是我的错误代码,那么我会重新抛出我的异常。

   T ServiceCall<T>(string command, string rest_uri, object request)
    {
        try
        {   
                if (command == "POST")
                      return client.Post<T>(serverIP+rest_uri, request);

        }
        catch (WebServiceException err)
        {
           if (err.ErrorCode == "APIException" && err.ResponseStatus.Errors != null 
                          &&  err.ResponseStatus.Errors.Count > 0)
            {
                string  error_code = err.ResponseStatus.Errors[0].ErrorCode;
                string  path_info = err.ResponseStatus.Errors[0].FieldName;  
                string detail_error = err.ResponseStatus.Errors[1].ErrorCode; 

                 throw new  APIException(error_code,detail_error,path_info);           
            } 
        } finally {}
   }
于 2013-11-06T11:01:51.260 回答