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());
                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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With