Hemant Kumar
Hemant Kumar

Reputation: 4611

How can we do the Error Handling in ASP.NET MVC3 Razor?

I am a newbie to MVC3. I have done a MCV3 application for some CRUD operation.

Now I want to do some error handling in MVC3. I have seen an article here about Error Handling.

  1. Can some one please briefly explain about various methods of Error handling in MVC?
  2. Do we need to create any custom classes to handle Error Handling?

Upvotes: 1

Views: 5814

Answers (1)

Yasser Shaikh
Yasser Shaikh

Reputation: 47784

P.S I am answering this with my understanding on this super generic question.

1 - Can some one please briefly explain about various methods of Error handling in MVC?

For Global Error Handling
All you have to do is change the customErrors mode="On" in web.config page
Error will be displayed through Error.cshtml resides in shared folder.

Make sure that Error.cshtml Layout is not null.
[It sould be something like: @{ Layout = "~/Views/Shared/_Layout.cshtml"; }
Or remove Layout=null code block]
A sample markup for Error.cshtml:-

@{ Layout = "~/Views/Shared/_Layout.cshtml"; } 

@model System.Web.Mvc.HandleErrorInfo

<!DOCTYPE html>
<html>
<head>
    <title>Error</title>
</head>
<body>
    <h2>
        Sorry, an error occurred while processing your request.
    </h2>
    <p>Controller Name: @Model.ControllerName</p>
    <p>Action Name : @Model.ActionName</p>
    <p>Message: @Model.Exception.Message</p>
</body>
</html>

For Specific Error Handling
Add HandleError attribute to specific action in controller class. Provide 'View' and 'ExceptionType' for that specific error.
A sample NotImplemented Exception Handler:

public class MyController: Controller
    {
        [HandleError(View = "NotImplErrorView", ExceptionType=typeof(NotImplementedException))]
        public ActionResult Index()
        {
            throw new NotImplementedException("This method is not implemented.");
            return View();
        }
}

2 - Do we need to create any custom classes to handle Error Handling?

See this Implementing an Error-Handling Filter

You should also have a look at Elmah Library for error logging.

Upvotes: 3

Related Questions