简体   繁体   中英

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

The IHttpActionResult is a feature that was added in WebApi 2. The traditional methods from WebApi 1, ie 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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM