简体   繁体   中英

How to catch all exceptions in Web API 2?

I'm writing a RESTful API in Web API and I'm not sure how to handle errors effectively. I want the API to return JSON, and it needs to consist of the exact same format every single time - even on errors. Here are a couple of examples of what a successful and a failed response might look like.

Success:

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

Error:

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

If there is an exception - any exception at all, I want to return a response that is formed like the second one. What is the foolproof way to do this, so that no exceptions are left unhandled?

Implement IExceptionHandler .

Something like:

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

and in the configuration section of WebAPI ( public static void Register(HttpConfiguration config) ) write:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM