0

I read somewhere that TRY CATCH is not recommended in Web API methods.

I'm making the following call into a method and if all goes well, I want to return an Employee object along with Status 200 but if something goes wrong e.g. database call fails, etc. I want to return status 500. What's the right way to handle that code?

[HttpPost]
public async Task<IHttpActionResult> PostNewEmployeeAsync(Employee emp)
{

   var newEmployee = await RegisterEmployee(emp);
   return Ok(emp);

   // What if I had a database error in RegisterEmployee method. How do I detect the error and send InternalServerError()

}

private async Task<Employee> RegisterEmployee(Employee emp)
{
   // Call DB to register new employee, then return Employee object
}

2 Answers 2

1

Your code should return the error code that matches the case that you have, for example if your code couldn't find the required resource in the database return NotFound,

but if you code raises an exception, avoid wrapping your code by try/catch block and instead the exception should bubble up to the level that you can handle it globally, to do this you have many options like :

1- Implement an ExceptionFilter where you can handle all the unhandled exceptions raised in your controllers (this doesn't include any exception happens before the controllers in the pipeline).

See this for more details about ExceptionFilterAttribute.

2- If you are using Web API 2, you can implement the interface IExceptionHandler where you can handle all the exception happens anywhere in the pipeline and there you can return the errors you want.

See this for more details about Global Exception Handling in Web API 2.

Hope that helps.

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

Comments

0

You don't want to avoid try/catch entirely, you just need to be really careful about it. Wrap your code in a try block, and catch the exception you're expecting. Inside the catch, return the error response.

2 Comments

Yes, that's exactly what I was doing but not sure why try catch is a bad idea in Web API methods.
It's just a bit more dangerous if you do it wrong, so you need to use self-contained exception handling to prevent exploitation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.