Reputation: 20350
As I ask this question, I'm mainly thinking about bad parameters. Parameters where:
int
<= 0string
is empty or whitespaceHere are the two error handling scenarios I'm talking about:
public ActionResult GoToError(int value, string name)
{
if (value <= 0 || string.IsNullOrWhiteSpace(name))
{
// Parameter(s) not meeting basic conditions
TempData["ErrorMessage"] = "Invalid parameters";
return RedirectToAction("Index", "Error");
}
return View();
}
public ActionResult ReturnView(int value, string name)
{
if (value <= 0 || string.IsNullOrWhiteSpace(name))
{
// Parameter(s) not meeting basic conditions
ViewData["ErrorMessage"] = "Invalid parameters";
return View("Error");
}
return View();
}
Upvotes: 2
Views: 1332
Reputation: 13497
There are different scenarios, that need to be handled differently:
Controller.OnException(...)
method and/or the asp.net custom error pagesBased on what you've posted, I can't classify weather they're 'anticipated' or 'unanticipated.' The main question is, how does the client of these calls expect them to be handled?
Upvotes: 1
Reputation: 33098
Doing errors properly in ASP.NET is just short of nightmare-ishly hard.
If you follow what the web is meant to do:
You should return an error result for any impossible to recover from error, like 400 bad request, 404 resource not found, etc. This includes most of the errors in the 4xx range.
For application errors that are unhandled exception that will result in a 500 error, the correct solution is to issue a 302 redirect to an error page that properly returns the 500 status code.
As @Darin Dimitrov said, in RESTful applications, you should never issue a redirect for anything it should always return the result definitively.
Upvotes: 0
Reputation: 1038730
In a RESTFul application you should return the view and set the corresponding HTTP status code (401, 403, 404, 500, ...). When you redirect this means status code 200 and returning status code 200 for an error page doesn't make sense. Here's a technique that I use to handle errors. This works also very nicely with AJAX when you can subscribe for different status codes. For example let's suppose that you have an authenticated site where logged in users can perform AJAX requests. After certain inactivity their session could expire and when they need to perform some AJAX request if your server doesn't return proper status code (401 in this case) the client script will have hard time understanding and handling the scenario.
Upvotes: 0