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);
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…