【问题标题】:How to catch all exceptions in Web API 2?如何捕获 Web API 2 中的所有异常?
【发布时间】:2014-10-13 06:16:24
【问题描述】:

我正在用 Web API 编写一个 RESTful API,但我不确定如何有效地处理错误。我希望 API 返回 JSON,并且每次都需要包含完全相同的格式 - 即使出现错误。以下是成功和失败响应的几个示例。

成功:

{
    Status: 0,
    Message: "Success",
    Data: {...}
}

错误:

{
    Status: 1,
    Message: "An error occurred!",
    Data: null
}

如果有异常 - any 异常,我想返回一个像第二个一样形成的响应。什么是做到这一点的万无一失的方法,以便没有未处理的异常?

【问题讨论】:

    标签: c# asp.net asp.net-web-api2


    【解决方案1】:

    实现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);
        }
    }
    

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

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

    【讨论】:

    • 这种方法似乎将Content-Type 设置为text/plain,而不是application/json
    • 不,不是。刚刚在我自己的代码中检查了它,它一直返回application/json
    • 有没有办法使用内容协商来做到这一点?
    • 我必须将 System.Runtime.Serialization 属性添加到我的自定义错误响应对象以获取 XML。没有属性的 web api 会退回到 json。
    • @Ofer Zelig 这些更改在 CreateResponse 中传递 JsonType,然后返回“Content-Type application/json”而不是“Content-Type text/plain”。我在默认的 Web API 2 配置中进行了测试。
    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 2017-03-30
    • 2019-08-07
    • 2010-09-11
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    相关资源
    最近更新 更多