如何捕获Web API 2中的所有异常?

Nic*_*oad 12 c# asp.net asp.net-web-api2

我在Web API中编写RESTful API,我不确定如何有效地处理错误.我希望API返回JSON,它需要每次都包含完全相同的格式 - 即使出现错误.以下是一些成功和失败的响应可能是什么样子的例子.

成功:

{
    Status: 0,
    Message: "Success",
    Data: {...}
}
Run Code Online (Sandbox Code Playgroud)

错误:

{
    Status: 1,
    Message: "An error occurred!",
    Data: null
}
Run Code Online (Sandbox Code Playgroud)

如果有异常 - 任何异常,我想返回一个像第二个那样形成的响应.什么是万无一失的方法,以便没有任何例外处理未处理?

Ofe*_*lig 12

实施IExceptionHandler.

就像是:

 public class APIErrorHandler : IExceptionHandler
 {
     public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)
     {
         var customObject = new CustomObject
             {
                 Message = new { Message = context.Exception.Message }, 
                 Status = ... // whatever,
                 Data = ... // whatever
             };

        //Necessary to return Json
        var jsonType = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        json.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;    

        var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError, customObject, jsonType);

        context.Result = new ResponseMessageResult(response);

        return Task.FromResult(0);
    }
}
Run Code Online (Sandbox Code Playgroud)

并在WebAPI(public static void Register(HttpConfiguration config))的配置部分写:

config.Services.Replace(typeof(IExceptionHandler), new APIErrorHandler());
Run Code Online (Sandbox Code Playgroud)