Sam
Sam

Reputation: 30396

Proper way to send Web API response

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
}

Upvotes: 0

Views: 125

Answers (2)

Omar.Alani
Omar.Alani

Reputation: 4130

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.

Upvotes: 1

Colin vH
Colin vH

Reputation: 537

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.

Upvotes: 0

Related Questions