Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I return a status code or throw an exception in .Net Web Api 2

I have seen examples like this

public IHttpActionResult GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return Ok(item);
}

But I have also imagine this is an option

public IHttpActionResult GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        return NotFound();
    }
    return Ok(item);
}

Is there an advantage to throwing an exception or simply returning a NotFound (IHttpActionResult instance)?

I know there are stages in the response / request pipeline where either of these results can be handled, like this for the first example

public class NotFoundExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is NotFoundException)
        {
            // Do some custom stuff here ...
            context.Response = new HttpResponseMessage(HttpStatusCode.NotFound);
        }
    }
}

...

GlobalConfiguration.Configuration.Filters.Add(
    new ProductStore.NotFoundExceptionFilterAttribute());
like image 766
seangwright Avatar asked May 02 '15 17:05

seangwright


People also ask

How do you handle exceptions in Web API?

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.

How do I return an exception from Web API?

Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.

How do you handle exceptions in .NET core API?

To handle exceptions we can use the try-catch block in our code as well as finally keyword to clean up resources afterward. Even though there is nothing wrong with the try-catch blocks in our Actions in Web API project, we can extract all the exception handling logic into a single centralized place.


1 Answers

The IHttpActionResult is a feature that was added in WebApi 2. The traditional methods from WebApi 1, i.e. creating an HttpResponseMessage or throwing an HttpResponseException, are still available to you, but the IHttpActionResult was developed to streamline the process.

The IHttpActionResult Interface has one method:

public interface IHttpActionResult
{
    Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken);
}

The NotFound method simply creates a NotFoundResult which returns an empty response with HttpStatusCode.NotFound. This is essentially the exact same thing that throwing HttpResponseException(HttpStatusCode.NotFound) does, but in a more uniform syntax.

The IHttpActionResult interface also allows you to easily create custom ActionResult classes to return any HttpStatusCode or any content type you wish.

like image 165
Claies Avatar answered Oct 27 '22 08:10

Claies