Exception handling is more important for any application, it is a process to handle the runtime errors and allows the application to run smoothly. We can handle the exceptions in AsP.NET MVC in many ways as shown below,
- Try-catch-finally
- Exception filter
- Using the [HandleError] attribute - Default
- Overriding OnException method - Customized
- Local
- Global (Associated with attribute)
- Application_Error event
- Extending HandleErrorAttribute
Try-catch-finally
This is one of the commonly used exception handling methods in ASP.NET MVC applications. To begin with, Create an ASP.NET MVC application using Visual Studio.
Once you have created an ASP.NET application, the structure seems like below,
You will see the HomeController.cs and Error.cshtml view under the "Views/Shared" folder. We will use the "HomeController.cs" file for our demonstration.
public ActionResult Index()
{
int x = 1;
int y = 0;
int z = 0;
try
{
z = x / y; //it will create an exception.
}
catch (Exception ex)
{
return View("Error");
}
finally
{
// custom code here
}
return View();
}
In the above code, we intentionally generate an exception in the line "z = x / y". As you know if an error occurs in the try block then it automatically goto catch block and executes the code under the block. In this example, we wrote the code to redirect it to the error page as shown below. If you run this application then you will see the error page in the browser. Normally in a production environment, we will use a catch block to log the error details.
Using the [HandleError] Attribute
We can use the HandleError
attribute to handle the errors easily in ASP.NET MVC applications. In order to use this attribute, first, we need to add "<customErrors mode="On" ></customErrors>
" line in web.config file under "System.web".
<system.web>
<compilation debug="true" targetFramework="4.7.2"/>
<httpRuntime targetFramework="4.7.2"/>
<!-- Add this line --->
<customErrors mode="On"></customErrors>
</system.web>
The HandleErrorAttribute
class is a built-in exception filter class in ASP.NET MVC that is used to render the Error.cshtml by default when an unhandled exception occurs.
We can handle multiple exceptions using HandleErrorAttribute
as shown below,
[HandleError(ExceptionType = typeof(DivideByZeroException), View = "Error1")]
[HandleError(ExceptionType = typeof(ArgumentOutOfRangeException), View = "Error2")]
[HandleError]
public ActionResult Index()
{
int x = 1;
int y = 0;
int z = 0;
z = x / y; //it will create an exception.
return View();
}
When we run the application, the error (System.DivideByZeroException: 'Attempted to divide by zero.') occurs because of the line "z = x / y;" the error1 page will be redirected because of the attribute [HandleError(ExceptionType = typeof(DivideByZeroException), View = "Error1")]
.
Comments (0)