ASP.NET MVC exception handling - asp.net-mvc

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

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.

ErrorAttribute vs OnException vs Application_Error

I want to handle application wide error and show a ErrorView page in asp.net mvc.
There are 3 ways to do it (or i know).
1) ErrorAttribute in BaseController:Controller class.
Can be used on individual Action/Controller/BaseController.
2) Override OnException() in the BaseController:Controller class.
Will work on Controllers derived from BaseController
3) Application_Error in Global_aspx.
What is the best practice.
Which one of these methods should be used for application wide error handling or should we use multiple or only one.
If we handle error on ErrorAttribute Or/And OnException() on BaseController should we still handle it in Application_Error().
When should we use Application_Error()?
HandleErrorAttribute is an MVC filter applied via the attribute. You can supply a view name to display if an exception occurs and you can also specify the base (or specific) type of exception this filter applies to. If no view name is supplied it will look for a view named "Error". As you've already noticed you can apply it to various scopes. It allows you to specify a different "error page" view based on the exception.
Controller.OnException is a method that will get called if any of your actions ends up throwing an error.
Both of the above two are MVC concepts and part of the MVC pipeline, which sits on top of the ASP.NET pipeline, and if you handle the exception using the above it won't propagate to Application_Error, but things like http errors 404, 500 and will if I remember correctly.
What to use?
Definitely look into ELMAH for application wide error logging and my blog post about ELMAH and ASP.NET MVC
Regarding displaying error pages you should be fine with just using [HandleError] and the HandleErrorAttribute, since it already handles everything for you (optional filtering and optional custom error page per exception type).
if you want to handle the error on application level then don't apply the HandleError or OnException Override for the controller.
Try to Get the Last Error from the Server Object in Application_Error Handler check the Exception Type and based on the exception type define the action you would like to perform.
For 404 you might want to set a different action on the controller to handle.
For 500 you might want to set a different action on the controller to handle.
For NON HTTPException (SQLException) you might even want to send out email.
Please make sure you set the correct Response Status Code for SEO purpose.

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."

Resources