mimarcel
mimarcel

Reputation: 695

How to handle only a specific type of Exception using the HandleError and let the rest of the Exceptions be thrown normally?

I'm working on a team-project and I am in the following situation:

I created my own Exception class, and I want all the thrown exceptions of type myException to be handled and automatically redirected to the Error view where I would nicely display the error, which is ok to do. This is what I added in my Web.config:

<customErrors mode="On" defaultRedirect="Error" />

The issue is I want all the rest of the exceptions to be thrown normally, seeing all the information about it, including the stack trace, the source file and the line error, which would be really good for the team-project.

I've tried the [HandleError(ExceptionType=typeof(myException)], but it is no use.

I also tried to override the OnException function of the controller and if the exception is not myException then i would throw it again, but i still get in the Error view.

protected override void OnException(System.Web.Mvc.ExceptionContext filterContext)
{
    if (filterContext.Exception.GetType() != typeof(myException)) {
        throw filterContext.Exception;
    }
    base.OnException(filterContext);
}

Any idea which could work?

Thanks.

Upvotes: 0

Views: 1830

Answers (1)

Bogdan Banut
Bogdan Banut

Reputation: 101

You may get the result you want by leaving custom errors Off (so that for all the errors you get the stack trace displayed), and redirecting the exceptions you want to the controller/view you need (so that a friendly-looking page will be displayed).

You could define a base controller for all your controllers, and override its OnException method with something like below:

        if (filterContext.Exception.GetType() == typeof(YourCustomException))
        {
            filterContext.ExceptionHandled = true;
            filterContext.Result = RedirectToAction("ActionName", "ControllerName", new { customMessage  = "You may want to pass a custom error message, or any other parameters here"});
        }
        else
        {
            base.OnException(filterContext);
        }

Upvotes: 3

Related Questions