5

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());
seangwright
  • 17,245
  • 6
  • 42
  • 54

2 Answers2

4

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.

Claies
  • 22,124
  • 4
  • 53
  • 77
2

Throwing an exception is always should be considered as an exceptional case. While being rare, it still can happen and should be handled properly.

It depends on how often do you need to retrieve nonexistent items from your database. Keep in mind that often exception throwing is always a performance killer.

You should also look into this:

When to throw an exception?

Community
  • 1
  • 1
AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • 2
    While that is true for normal desktop/app programming, I think WebAPI uses exceptions a little differently so I don't know if this advice is as valid as it normally is. – Scott Chamberlain May 02 '15 at 18:13