2016-08-19 61 views
1

提出我們開發ASP.NET MVC5應用與WebApi2AngularJs如何在全球範圍內ASP.NET的WebAPI處理異常。序列化和反序列化,我們用俗JsonNetFormatter如下:異常時通過JsonNetFormatter

public class JsonNetFormatter : MediaTypeFormatter 
{ 

    // other codes for formatting 

    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext) 
    { 
     string NameOfSet = ""; 
     ObjectWrapperWithNameOfSet obj = value as ObjectWrapperWithNameOfSet; 
     if (obj != null) 
     { 
      NameOfSet = obj.NameOfSet; 
      value = obj.WrappedObject; 
     } 

     _jsonSerializerSettings.ContractResolver = new CustomContractResolver(NameOfSet); 

     // Create a serializer 
     JsonSerializer serializer = JsonSerializer.Create(_jsonSerializerSettings); 

     // Create task writing the serialized content 
     return Task.Factory.StartNew(() => 
     { 
      using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, SupportedEncodings[0])) { CloseOutput = false }) 
      { 
       serializer.Serialize(jsonTextWriter, value); 
       jsonTextWriter.Flush(); 
      } 
     }); 
    } 
} 

和WebApiConfig如下:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     // Web API configuration and services 

     // Web API routes 

     config.Formatters.Clear(); 
     config.Formatters.Insert(0, new JsonNetFormatter()); 
    } 
} 

應用做工精細。但在某些情況下,當反序列化json數據時會出現錯誤。我的問題是我們如何處理這些錯誤併發送給客戶端?

例的錯誤:

enter image description here

回答

1

您可以創建自己的自定義異常處理程序將其發送到客戶端

public class ErrorHandler : ExceptionHandler 
    { 
     public override void Handle(ExceptionHandlerContext context) 
     { 

      context.Result = new TextPlainErrorResult() 
      { 
       Request = context.ExceptionContext.Request, 
       Content = "Oops! Sorry! Something went wrong." + "Please contact support so we can try to fix it." 
      }; 
     } 

     private class TextPlainErrorResult : IHttpActionResult 
     { 
      public HttpRequestMessage Request { get; set; } 

      public string Content { get; set; } 

      public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
      { 
       HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError, Content); 
       return Task.FromResult(response); 
      } 
     } 
    } 

之前修改任何錯誤消息,然後在註冊這個自定義類config類如下

config.Services.Replace(typeof(IExceptionHandler), new ErrorHandler());