tags:

views:

36

answers:

1

I'm trying to make a request for a customer and if the customer doesn't exist it should return some kind of "Not found" page. Which of the below would be the best practice to use for such a task, and why?

public ActionResult Index(int id)
{
    if (customerService.GetCustomerById(id) == null)
        return View("NotFound");

    return View();
}

or

public ActionResult Index(int id)
{
    if (customerService.GetCustomerById(id) == null)
        throw new HttpException(404, "Customer not found");

    return View();
}
+3  A: 

This is a good question (+1) as there are some differing opinions out there about when to use HTTP exception codes and when not.

REST disciples will likely tell you to go the HTTP Exception route because they believe that a URI identifies a conceptual resource (i.e.: the actual object/thing to which you are referring - a Customer in this case), and if that resource doesn't exist then you should get a 404 error back.

However, some will disagree and say that you should only pass back a 404 error if the physical resource, e.g. a file, doesn't exist.

I tend to fall into the second camp and would recommend that you return 200 OK with a custom view stating that the customer specified by the ID could not be found.

Brian Driscoll
A custom view that takes a parameter for error message, and response code as 200 would be the way forward?
ebb
That would be my recommendation, yes. Like I said, it's just an opinion and not necessarily a codified best practice, so really you can do whatever you want.
Brian Driscoll