2015-06-03 26 views
0

我有一个网络API我沟通。从Web API错误中筛选异常堆栈跟踪?

当异常发生时,我得到以下JSON模板:

{ 
    "Message": "An error has occurred.", 
    "ExceptionMessage": "Index was outside the bounds of the array.", 
    "ExceptionType": "System.IndexOutOfRangeException", 
    "StackTrace": " at WebApiTest.TestController.Post(Uri uri) in c:\\Temp\\WebApiTest\\WebApiTest\\TestController.cs:line 18\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClassf.<GetExecutor>b__9(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)" 
} 

我想要什么的JSON,包括只是“消息”和“ExceptionMessage”性质,但仍对返回整个堆栈控制追踪追踪。

我使用

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy 

尝试,但似乎这是全有或全无,要么只是单一的“消息”属性或设置它时,“总是”获得完整的对象。

任何简单的方法来实现这一目标?

援助将不胜感激。

回答

1

在我的代码使用异常过滤器做你所要求的信息,请查看以下两个链接了解更多详情

Web API Exception Handling

Web API global error handling

,我们做我们的代码是什么的如下:

  1. 创建异常过滤器:

    public class ViewRExceptionFilterAttribute : ExceptionFilterAttribute 
    { 
    // Global context message for the modifying the context response in case of exception 
    private string globalHttpContextMessage; 
    
    /// <summary> 
    ///  Overriding the OnException method as part of the Filter, which would detect the type of Action and would 
    ///  accordingly modify the Http 
    ///  context response 
    /// </summary> 
    /// <param name="context"></param> 
    public override void OnException(HttpActionExecutedContext context) 
    { 
        // Dictionary with Type and Action for various Type actions, current method is called by various types 
        Dictionary<Type, Action> dictionaryExceptionTypeAction = new Dictionary<Type, Action>(); 
    
        // Add an action for a given exception type 
        dictionaryExceptionTypeAction.Add(typeof (ViewRClientException), ViewRClientExceptionAction(context.Exception));    
        dictionaryExceptionTypeAction.Add(typeof (Exception), SystemExceptionAction(context.Exception)); 
    
        // Execute an Action for a given exception type 
        if (context.Exception is ViewRClientException) 
         dictionaryExceptionTypeAction[typeof (ViewRClientException)](); 
        else 
         dictionaryExceptionTypeAction[typeof (Exception)](); 
    
        // Reset the Context Response using global string which is set in the Exception specific action 
        context.Response = new HttpResponseMessage 
        { 
         Content = new StringContent(globalHttpContextMessage) 
        }; 
    } 
    
    /// <summary> 
    ///  Action method for the ViewRClientException, creates the Exception Message, which is Json serialized 
    /// </summary> 
    /// <returns></returns> 
    private Action ViewRClientExceptionAction(Exception viewRException) 
    { 
        return (() => 
        { 
         LogException(viewRException); 
    
         ViewRClientException currentException = viewRException as ViewRClientException; 
    
         ExceptionMessageUI exceptionMessageUI = new ExceptionMessageUI(); 
    
         exceptionMessageUI.ErrorType = currentException.ErrorTypeDetail; 
    
         exceptionMessageUI.ErrorDetailList = new List<ErrorDetail>(); 
    
         foreach (ClientError clientError in currentException.ClientErrorEntity) 
         { 
          ErrorDetail errorDetail = new ErrorDetail(); 
    
          errorDetail.ErrorCode = clientError.ErrorCode; 
    
          errorDetail.ErrorMessage = clientError.ErrorMessage; 
    
          exceptionMessageUI.ErrorDetailList.Add(errorDetail); 
         } 
    
         globalHttpContextMessage = JsonConvert.SerializeObject(exceptionMessageUI, Formatting.Indented); 
        }); 
    } 
    

这里ViewRClientException是我的自定义异常类与下面的模式:以上定义

public class ViewRClientException : Exception 
{ 
    public ViewRClientException(ErrorType errorType, List<ClientError> errorEntity) 
    { 
     ErrorTypeDetail = errorType; 
     ClientErrorEntity = errorEntity; 
    } 

    public ErrorType ErrorTypeDetail { get; private set; } 
    public List<ClientError> ClientErrorEntity { get; private set; } 
} 

操作方法确保我们能得到相关的JSON序列串,它可以作为JSON响应,类似的是SystemExceptionAction的作用是任何一般的异常,这不是自定义的。事实上,我有很多其他的自定义异常类别。电流滤波器修改HttpContext.Response

  • 注册在WebAPIConfig.cs例外滤波器,如下所示:

    public static class WebApiConfig 
        { 
         public static void Register(HttpConfiguration config) 
         { 
         // Web API configuration and services 
    
         // Adding the Generic Exception Filter for the application 
         config.Filters.Add(new ViewRExceptionFilterAttribute()); 
    
         // Web API routes 
         config.MapHttpAttributeRoutes(); 
    
         config.Routes.MapHttpRoute("ControllerActionApi", "api/{controller}/{action}/{userID}", 
          new {userID = RouteParameter.Optional} 
          ); 
    
         config.Routes.MapHttpRoute("ControllerApi", "api/{controller}/{userID}", 
          new {userID = RouteParameter.Optional} 
          ); 
         } 
        } 
    
  • 现在它应该工作提供定制当你需要的信息

    +0

    谢谢,我会研究它。 –

    +0

    对我来说它完美无瑕。您可以使用自定义例外 –

    -2

    不完整的例子。 ClientError & ErrorType错误类型详细信息

    如果您要投稿,请包括所有内容!

    +1

    使用您需要的格式获取数据的基本要求,请使用“评论”链接进行评论,并保存实际答案的“答案”链接 –