Santhosh
Santhosh

Reputation: 20406

custom error page in mvc

I need to show up the error page using customerror on web.config

But watever the error may be, even in web.config i specified some version wrong also it need to show the error page,

How can I do this. I tried but url redirects to

"http://localhost:1966/Error.html?aspxerrorpath=Error.html"

CustomError Tag:

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

And shows up another error page from mvc, not mines.

Upvotes: 3

Views: 5960

Answers (2)

Webking
Webking

Reputation: 1862

You can use the solution as Mark described above HandleError attrib.

Another solution to catch errors is to have a baseclass the all you controller class derives from. And inside the baseclass ovveride OnException method to show a user friendly error view that you have in for example "~/Shared/Error.aspx"

You also need to have <customErrors mode="On" > defined in your root web.config for this solution to work.

public class BaseController : Controller
{
        ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

    public BaseController()
    {
    }

    protected override void OnException(ExceptionContext filterContext)
    {
        // Log the error that occurred.
        log.Fatal("Generic Error occured",filterContext.Exception);

        // Output a nice error page
        if (filterContext.HttpContext.IsCustomErrorEnabled)
        {
            filterContext.ExceptionHandled = true;
            View("Error").ExecuteResult(ControllerContext);
        }
    }

}

Above solution catches most of the possible "yellow screen of death errors" that occurs.

To handle other errors like 404 i use folowing mapRoute last in global.asax RegisterRoutes(RouteCollection routes)

// Show a 404 error page for anything else.
            routes.MapRoute(
                "Error",
                "{*url}",
                new { controller = "Shared", action = "Error" }
            );

Upvotes: 1

Mark Seemann
Mark Seemann

Reputation: 233125

In ASP.NET MVC error handling is normally specified using the HandleError attribute. By default, it uses a View named 'Error' to display the custom error page. If you just want to customize this View, you can edit Views/Shared/Error.aspx.

If you want a different View in particular cases, you can explicitly supply the View property.

Here's an example of a Controller action with a custom Error View:

[HandleError(View = "CustomError")]
public ViewResult Foo() 
{
    // ...
}

For global error handling in ASP.NET MVC, see this post.

Upvotes: 7

Related Questions