ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

How to use Exception filters in ASP.NET Core MVC?

.Net .Net Core about 7 years ago || 9/28/2018 || 4.9 K View

  • Hide

In ASP.NET Core MVC we have the option to filter Exceptions in MVC execution pipeline, and it's handy too, for developer as we know when it comes no one like, so having an option to handle it seems interesting, in ASP.NET framework also we have the option to handle it, but as we are focusing on ASP.NET Core MVC in this post, let's see some important note on Exception filter.

What is Exception filter?
A custom class where we can write our logic to execute on action method execute in ASP.NET Core MVC. It is used to apply global policies to unhandled exceptions which can occur before anything has been written to the response body.

Exception filter implements either IExceptionFilter or IAsyncExceptionFilter interface, not both. We can use to implement common error handling policies for an application.

Note:- Unlike other filter Exception filter doesn't have before and after events.

A simple custom class from docs.microsoft.com looks like,

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    private readonly IHostingEnvironment _hostingEnvironment;
    private readonly IModelMetadataProvider _modelMetadataProvider;

    public CustomExceptionFilterAttribute(
        IHostingEnvironment hostingEnvironment,
        IModelMetadataProvider modelMetadataProvider)
    {
        _hostingEnvironment = hostingEnvironment;
        _modelMetadataProvider = modelMetadataProvider;
    }

    public override void OnException(ExceptionContext context)
    {
        if (!_hostingEnvironment.IsDevelopment())
        {
            // do nothing
            return;
        }
        var result = new ViewResult {ViewName = "CustomError"};
        result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState);
        result.ViewData.Add("Exception", context.Exception);
        // TODO: Pass additional detailed data via ViewData
        context.Result = result;
    }
}

 

Exception filter

  • Exception filter implement OnException or OnExceptionAsync
  • Handle unhandled exceptions that can occur in controller actions, model binding, action filters, or action methods.
  • Exception filter can't turn an exception into a "success". Only an Action filter can do that. To know more about Action filter check Action filter
  • We do not catch exceptions that can occur in Resource filters, Result filters, or MVC Result execution.

 

Note:- Exception filter is good for Trapping exceptions that occur within MVC actions & are not as flexible as error handling in middleware.

 

Prefer middleware for exception handling. Use exception filters only where we need to do error handling differently based on which MVC action was chosen.

  • 1
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Alok Pandey

Alok Pandey

Love to share what I know.

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey