What Error Handling Options Do I Have In ASP.NET MVC? - asp.net-mvc

What options do I have for error handling in ASP.NET MVC?
Do I call GetLastError on the error page and send out the email or log it?

Why not an error handling filter?

In your Global.asax you can implement something like the following:
protected void Application_Error()
{
Exception lastException = Server.GetLastError();
GetLogger().Fatal(lastException); // your custom loggin code
}

McvContrib has "Rescue" attributes -- an idea borrowed from Monorail. You can do like so:
[Rescue("default", AutoLocate = true)]
public class MyController : ConventionController
You then create rescue views based on convention like so:
Views/Shared/Rescues/Exception.aspx
Views/Shared/Rescues/MyCustomException.aspx
Etc. When an unhandled exception occurs in a controller, the rescue filter will render the page with the same name as the exception type. If no exact match is found it renders Exception.aspx. (I think maybe it works up the inheritence hierarchy till if finds a match.)
These rescue views implement ViewPage<HandleErrorInfo> so in the view page you access the exception as ViewData.Model.Exception. This is the one place where I put code in the codebehind -- to log the exception -- because it makes for a nice application boundary.
If you don't want to use MvcContrib, you can study the code to implement your own solution.

Related

Accessing the exception if custom redirection redirects to a controller

I am using MVC4, and would like to be able to throw HttpExceptions from a ontroller, and handle those in a seperate controler.
I have set up <customErrors mode="On" defaultRedirect="/Error"/> for this. This works, but in my controller I would like to be able to access the exception.
Preferably I would like to have two modes:
Handle instances of HttpException, so that from a controller I can throw a HttpException and have it handled accordingly
Handle all other errors.
in case of the first, I would like to present the useragent with the appropriate status code, and possibly a view. In case of the second I want to present the useragent with status 500, and show a default view with an optional message.
For this, I think I need to access the exception data - at least, I can't think of any other proper way to do this.
What is the proper way to set this up? I know there are plethoria of other questions on error handling in MVC, yet none seem to answer these questions.
but in my controller I would like to be able to access the exception.
Have you tried Server.GetLastError:
Exception ex = Server.GetLastError();
Server.GetLastError() - should be used in Application_Error in global.asax, in that case you can handle last error like described here, besides you should remove
filters.Add(new HandleErrorAttribute());
in FilterConfig.cs
for more info look at:
Application_Error not firing when customerrors = "On"
ASP.NET custom error page - Server.GetLastError() is null
http://www.secretgeek.net/custom_errors_mvc.asp
http://devstuffs.wordpress.com/2010/12/12/how-to-use-customerrors-in-asp-net-mvc-2/

MVC HandleError filter didn't catch an exception

I've an MVC 3 web app in which I'm using "HandleError" Action Filter for exception handling. I've this action filter implemented as follows:
[HandleError]
public class BaseController : Controller {...}
This is the base class from which all of my controllers are derived. In my web.config I've and there's an Error.cshtml in my Shared folder (.cshtml because I use Razor). Everything has been working fine and I get a fine exception handling (formatted by my function)
Recently, somehow I got and "unhandled exception (YSOD)" and because of "customErrors" I got the default ASP.Net error message which didn't have any info about the actual exception. This happened in an AJAX post back. However, I'm unable to reproduce it.
Is it possible for any sort of errors to escape this action filter?
Is it possible for any sort of errors to escape this action filter?
HandleError filter doesn't catch all the exceptions fired in an application. It can capture exceptions that are fired inside actions, action filters.. simply inside the MVC context. Also it doesn't capture HTTP exceptions having status code other than 500. Relying only on HandleError filter in an MVC application is a bad idea.
You should still rely on the Application_Error event to do some logging and customErrors section to display a custom error page for the exceptions that are not captured by HandleError.
I've written a blog post on this subject that may help you.

Proper Exception Handling with ASP.NET MVC, ELMAH and custom Error Pages

consider the following situation:
There is an ASP.NET MVC application which utilizes ELMAH for centralized ExceptionLogging. A Controller is marked with the HandlerError Attribute to catch a specific type of an exception and presents the user with a view. For example
[HandleError(ExceptionType = typeof(ModelSpecificException), View = "Exceptions/ModelSpecific")]
public partial class HeavyController : Controller
{
// Constructors and ActionResults are following here...
}
This is working as expected so far. The problem I am facing right now is, that the "ModelSpecific" error page is needing some Objects within the ViewData. Does anyone has a hint on populating the ViewData Dictionary of a ViewPage of following Type
System.Web.Mvc.ViewPage<HandleErrorInfo>
Another idea which comes to my my mind is, that maybe a Controller could be used for the ErrorHandling with respective ActionResults. But currently I don't have a clue on how to accomplish that.
Any help is very appreciated...
best regards,
Gordon
Since both your exception class and the view are model specific, could you store the extra data you need in the exception itself?
if(badCondition)
{
throw new ModelSpecificException("a bad thing happened", extraData);
}
In your view you can get the exception via Server.GetLastError() and then cast it to the correct type to access the extra data via properties. This might be a cleaner approach since it treats the exception as the model and keeps you out of the ViewData collection.

How to redirect to error page in view in MS ASP.NET MVC?

In Controller, RedirectToAction("Error") can redirect to error page. How to write code in view code to allow the page redirected to error.aspx view?
You shouldn't need to handle reporting of errors inside MVC actions, and hard coding error behaviour makes finding a fixing issues harder than it needs to be.
Instead use the HandleError attribute and throw a regular exception:
[HandleError]
public class ThingController : Controller
{
public ActionResult DoStuff()
{
...
// uh-oh! throw exception
throw new WhateverException("message");
}
}
This will allow you to use the customErrors config flag to change your application's behaviour:
<customErrors mode="RemoteOnly" defaultRedirect="~/System/Error" />
Then locally you'll get an ugly but detailed yellow screen of death, plus debug will break on the thrown exception by default.
Remote users will get redirected to your SystemController.Error where you can have a nice user-friendly message and log the error.
This will work for controller actions and views in the same way.
#Jørn is right, but what kinds of errors are you predicting to show up in your view?
If you gave some details on why you're thinking about this, we might be able to suggest some better alternatives instead of simply saying "don't do this."

ASP.NET MVC exception handling

Is it OK to catch my exceptions in the controller's actions? Is there any better way of doing it? I'm actually catching my exceptions in the controller and using TempData to show a message to the user, but I have a weird feeling about this approach. I've been browsing around but I haven't found anything that suits me.
You can use the HandleError attribute on the controller class to catch any unhandled exceptions and it will automatically return the Error.aspx view in the Shared folder. There are overloads for this attribute so you can only have it used for certain exception types, etc.
For more information on this approach, check out ScottGu's post about it: http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx

Resources