Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Errors in Web API

I'm developing a brand new REST API using ASP.NET Web API. Coming from a WCF background, I feel drawn to creating "error contracts" for my API.

In this case, I'm not talking about unhandled exceptions being returned to the client. Instead, I'm focusing on errors such as the API being used improperly by the client - especially those where the client can automatically create these errors and resubmit the requests.

Most examples I've found just have a string being returned, usually by throwing an HttpResponseException, or at least doing some stuff to make the process of building up an informative error string more automated: Return custom error objects in Web API

I'm thinking about instead creating an HttpResponseException, passing in an HttpResponseMessage whose content is set to my specific error contract type.

My API is also making heavy use of automatic model validation, though, and those model validation errors come back as a totally different structure.

So should I force my "errors" into the same format as the model validation responses? What are the best practices here?

Lastly, my API will expose formatting options of json, xml, and protocol buffers. As a result, I really need to make sure that my strategy is formatter-independent.

like image 706
RMD Avatar asked May 26 '13 02:05

RMD


2 Answers

I wrote this blog post a while back about how Web API does error handling:

http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

It should help answer your questions. Essentially, you have two options:

  1. Define your own class for error responses. In this case, you want to ensure your class can be serialized as XML, JSON, etc. Then you can use Request.CreateResponse(statusCode, myErrorInstance) to send back your custom errors. You probably also want a way to turn invalid model states into your particular error type.

  2. Use Web API's error response type: HttpError. HttpError is essentially a Dictionary<string, object> where you add your own keys and values to the HttpError. The advantages are many - your errors will look like Web API errors, you know it works with all formatters, and you can avoid the work of having to define transformations from exceptions and invalid model states. The easiest way to use HttpError is calling Request.CreateErrorResponse().

like image 136
Youssef Moussaoui Avatar answered Sep 30 '22 14:09

Youssef Moussaoui


You can do anything you want in these situations. The best experience for the consumer of your web api would be to make sure that you use friendly error messages, in which case you'll want to serialize your errors into well formatted json objects. The following blog post provides some use cases and a solution that I have come up with: Web Api, HttpError and the Behavior of Exceptions

like image 31
Andy Cohen Avatar answered Sep 30 '22 13:09

Andy Cohen