Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for error handling with ASP.NET Web API

Could you clarify what is the best practice with Web API error management. Actually, I don't know if it is a good practice to use try catch into 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 have the feeling using try catch to a server side code is not a good practice because I just log my catch en re-throw an exception.

like image 372
Bastien Vandamme Avatar asked Jun 25 '16 05:06

Bastien Vandamme


People also ask

How does ASP net handle Web API errors?

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 do you handle errors in API?

The simplest way we handle errors is to respond with an appropriate status code. Here are some common response codes: 400 Bad Request – client sent an invalid request, such as lacking required request body or parameter. 401 Unauthorized – client failed to authenticate with the server.

What are the different ways in which we can handle run time errors in Web API application code?

Exceptions are the errors that happen at runtime. Exception handling is the technique to handle this runtime error in our application code. If any error is thrown in web API that is caught, it is translated into an HTTP response with status code 500- "Internal Server Error".


2 Answers

Error handling in Web API is considered a cross-cutting concern and should be placed somewhere else in the pipeline so the developers doesn’t need to focus on cross-cutting concerns.

You should take a read of Exception Handling in ASP.NET Web API

What happens if a Web API controller throws an uncaught exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.

and also Global Error Handling in ASP.NET Web API 2

You should try to keep your controller lean as much as possible. Error handling like your original code will only result in duplication of code, and unnecessary concerns for the developers to be aware of. Developers should focus on the core-concern, not the cross-cutting concerns. By just focusing on the core-concern the above code will look like this:

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

Why so lean?

Because :

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

can be moved into Authentication Filters in ASP.NET Web API 2 that can be applied locally on the controller/action or globally to return a relevant response.

Model Validation in ASP.NET Web API like this

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

Can also be moved into a filter like : .

public class MyValidateModelAttribute : ActionFilterAttribute {     public override void OnActionExecuting(HttpActionContext actionContext)     {         if (!actionContext.ModelState.IsValid)         {             actionContext.Response = actionContext.Request.CreateErrorResponse(                 HttpStatusCode.BadRequest, actionContext.ModelState);         }     } } 
like image 53
Nkosi Avatar answered Oct 08 '22 16:10

Nkosi


Please refer to this link Exception Handling in ASP.NET Web API - A Guided Tour. There are 4 level exception handling pipeline:

  • Level 1 - HttpResponseException
  • Level 2 - Exception Filters
  • Level 3 - Logging
  • Level 4 - Exception Handlers

Web API provides us a great deal of flexibility in terms of exception handling. To recap:

  • Use HttpResponseException or the shortcut methods to deal with unhandled exceptions at the action level.
  • Use Exception Filters to deal with particular unhandled exceptions on multiple actions and controllers.
  • Use ExceptionLogger to log any unhandled exception.
  • Use Exception Handlers (one per application) to deal with any unhandled exception application-wide.
like image 30
Phuc Thai Avatar answered Oct 08 '22 15:10

Phuc Thai