Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 867
Nick Coad Avatar asked Aug 20 '14 01:08

Nick Coad


People also ask

How do I get exceptions in Web API?

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.

How does Web API handle exception globally?

Global Exception Filters With exception filters, you can customize how your Web API handles several exceptions by writing the exception filter class. Exception filters catch the unhandled exceptions in Web API. When an action method throws an unhandled exception, execution of the filter occurs.

How does Web API handle 400 error?

BadRequest: 400 Error A 400 error, BadRequest, is used when you have validation errors from data posted back by the user. You pass a ModelStateDictionary object to the BadRequest method and it converts that dictionary into JSON which, in turn, is passed back to your HTML page.


1 Answers

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());
like image 156
Ofer Zelig Avatar answered Nov 15 '22 20:11

Ofer Zelig