1

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)); } 

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was unaware of this. I will have to look into that a bit more in depth. I'm assuming that the types of Exceptions you don't trap for will get thrown the same way as they normally would, correct?
Correct, you get to hook in and change behaviour or alternatively just pass on the opportunity

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.