Best practice for error handling using ASP.NET Web API

Could you please explain what is best suited for managing web API errors. Actually, I don't know if it is good practice to use try catch in my Api request.

public Vb.Order PostOrderItem(Vb.Order order) { if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized); throw new HttpResponseException(httpResponseMessage); } if (!ModelState.IsValid) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); throw new HttpResponseException(httpResponseMessage); } try { return Vb.Document.Generate(order); } catch (Exception ex) { logger.Error(ex); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); httpResponseMessage.Content = new StringContent(ex.Message); throw new HttpResponseException(httpResponseMessage); } } 

I feel that using try catch for server-side code is not a good practice, because I just log my catch en re-throw exception.

+7
c # exception-handling asp.net-web-api
source share
3 answers

Error handling in the Web API is seen as a cross-cutting issue and should be placed somewhere else in the pipeline, so developers do not need to focus on cross-cutting issues.

You should read Exception Handling in ASP.NET Web Interface

What happens if the web API controller throws an uncaught exception? From default, most exceptions are translated into the HTTP response using status code 500, Internal server error.

as well as global error handling in ASP.NET Web API 2

You should try to keep your controller as long as possible. Error handling, like the source code, will only lead to duplication of code and unnecessary problems for developers. Developers should focus on the core issue, not cross-cutting issues. Just focusing on the main problem, the code above will look like this:

 [MyAuthentication] [MyValidateModel] public Vb.Order PostOrderItem(Vb.Order order) { return Vb.Document.Generate(order); } 

Why so scarce?

Because:

 if (OAuth.isValid(Request.Headers.GetValues("Token").Single()) != true) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.Unauthorized); throw new HttpResponseException(httpResponseMessage); } 

can be moved to Authentication Filters in ASP.NET Web API 2 which can be applied locally on the controller / action or globally to return an appropriate response.

Testing the model in the ASP.NET web interface as shown

 if (!ModelState.IsValid) { HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest); throw new HttpResponseException(httpResponseMessage); } 

You can also move to the filter, for example :.

 public class MyValidateModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (!actionContext.ModelState.IsValid) { actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, actionContext.ModelState); } } } 
+16
source share

Please refer to this link. Exception Handling in ASP.NET Web Based Oriented Tour . There are 4 levels of exception handling:

  • Level 1 - HttpResponseException
  • Level 2 - Exceptional Filters
  • Level 3 - Registration
  • Level 4 - Exception Handlers

The Web API provides us with great flexibility regarding exception handling. Recall:

  • Use an HttpResponseException or quick access methods to handle unhandled exceptions at the action level.
  • Use exception filters to deal with specific unhandled exceptions for multiple actions and controllers.
  • Use ExceptionLogger to log any unhandled exception.
  • Use exception handlers (one for each application) to handle any unhandled exceptions in system-wide applications.
+8
source share

There are several methods, each step forward on the schedule of logical objects,

This article lists them all; http://www.codeproject.com/Articles/850062/Exception-handling-in-ASP-NET-MVC-methods-explaine

It’s useful for me to use one of the higher level methods to avoid code duplication.

+1
source share

All Articles