2015-06-03 25 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

    使用您需要的格式獲取數據的基本要求,請使用「評論」鏈接進行評論,並保存實際答案的「答案」鏈接 –