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