Home > DeveloperSection > Forums > How to catch all exceptions in Web API 2?
Ashish Pandey

Total Post:128

Points:898
Posted on    January-14-2015 10:10 PM

 ASP.Net C#  Exception Handling 
Ratings:


 1 Reply(s)
 669  View(s)
Rate this:

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?



Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    January-14-2015 10:42 PM

Implement IExceptionHandler.

Something like:

public class APIErrorHandler : IExceptionHandler

{

    public Task HandleAsync(ExceptionHandlerContext context, CancellationToken cancellationToken)

    {

        var jsonResult = Json.Encode(new

                                {

                                    Message = new { Message = context.Exception.Message },

                                    Status = ... // whatever,

                                    Data = ... // whatever

                                });

 

        context.Result = new ResponseMessageResult(new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(jsonResult) });

 

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


Don't want to miss updates? Please click the below button!

Follow MindStick