Is it possible to make my API always handle given exceptions? In every single method, I am catching DbEntityValidationExceptions and ValidationExceptions. Every method implements these catch the same way. Is there a way to delegate a routeine that my API or project can use anytime one of these errors gets thrown?
Here is an example of what every method looks like (Again this is an APIController to be specific):
try
{
//Do something
}
catch(ValidationException ex)
{
var errors = ErrorsAdd(new[] { ex.ValidationResult });
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, errors, _format));
}
catch (DbEntityValidationException ex)
{
var errors = ErrorsAdd(ex.EntityValidationErrors);
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, errors, _format));
}
Create a global filter that handles those exceptions and acts appropriately. In a default MVC site there should already be an ErrorFilter that handles all exceptions. You can create one just like it, except only handling specific errors.