ASP. Net core middleware global exception handling mechanism



We often hear“Second repair second online”, I think it’s very powerful.

In fact, it is not. This is just a joke. There are many ways to cause problems (logic vulnerabilities, code exceptions, incorrect operation methods, etc.).

Today, let’s talk about how to quickly locate code exceptions to reduce unnecessary time waste.

This is today’s topic “adding a global exception handling mechanism” to capture exceptions and store them in the database (mongodb, sqlserver, mysql, etc.).

PS: output TXT is not very friendly. Not everyone can log in to the server.

An exception is a runtime error. If an exception is not handled properly, it may cause your program to terminate unexpectedly.

1. Create project

We create aASP.NET Core Web APIProjects, selecting.NET Core3.1

2. Create global exception filter

Create an exception filter in the controller namedExceptionFilter.cs, filter inheritanceIExceptionFilterInterface.

Note that I useefcore+sqlserver, you can use it according to your actual situationORMAnd database mode.

Exception filter, as the name suggests, is the filter used when an exception occurs in a program. Used to handle uncaught exceptions in the system.

To implement a custom exception filter, you need to implement a custom global exception filterIExceptionFilterInterface.

 IExceptionFilterInterface will require implementationOnExceptionMethod, which will be triggered when an uncaught exception occurs in the system.

Onexception method has aExceptionContextException context, which contains specific exception information,HttpContextandmvcRouting information.

Once an uncaught exception occurs in the system, a common method is to use the logging tool to record the details of the exception for easy correction and debugging.

The following is the implementation of logging:

using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace Log4NetWebAPI.Controllers
    public class ExceptionFilter: IExceptionFilter
        //Global exception handling mechanism
        public void OnException(ExceptionContext context)
            Exception ex = context.Exception;

            //Controller method name where the error is
            var DisplayName = context.ActionDescriptor.DisplayName;

            #Region error line number line number

            ////Some of the names in front of the bank number are in Chinese and some are in English. Please pay attention to screening
            //var aaa = ex.StackTrace. Substring (ex.stacktrace.indexof ("line number"), ex.stacktrace Length - ex.StackTrace. Indexof ("line number");
            //var ccc = ex.StackTrace.Substring(ex.StackTrace.IndexOf("line"), ex.StackTrace.Length - ex.StackTrace.IndexOf("line"));
            var lineNumber = 0;
            const string lineSearch = ":line ";
            var index = ex.StackTrace.LastIndexOf(lineSearch);
            if (index != -1)
                var lineNumberText = ex.StackTrace.Substring(index + lineSearch.Length);
                var lineNumberStr = lineNumberText.Substring(0, lineNumberText.IndexOf("\r\n"));
                if (int.TryParse(lineNumberStr, out lineNumber))



            #Region writes information to the [database], where it can be stored by itself (mongodb, sqlserver, mysql, etc.). I take sqlserver as an example

            errorLog md = new errorLog();
            md.logTime = DateTime.Now;
            md.logType = "error";
            md.displayName = DisplayName;  // error location
            md.lineNumber = lineNumber;  // Wrong line number
            md.message = ex.Message;    // error message
            md.messagedetails = ex.ToString();  // Error details
            md.createTime= DateTime.Now;

            using (var ctx = new dbContext())


            //The following is the content prompt displayed on your return page, which is omitted below


3. Dependency injection global exception handling mechanism

stayStartup.csThe global exception handling mechanism we just created is injected into the middleware and put into theConfigureServicesMethod.

//Add global exception handling mechanism
services.AddMvc(option => {

// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)

            //Add global exception handling mechanism
            services.AddMvc(option => {

4. Test the global exception handling mechanism

“WillstringString is converted to int type “. The following code must be an error. Let’s capture the error information and store it in the database.

Var numberno = “I am the serial number”;
//Here, the data source is converted to int type, and the data source is string. The error must be reported, and then we capture it globally
//Note that we do not write try catch here
var number = Convert.ToInt32(numberNo);

After running the project, we checked the database and found that the error information was captured, including

Error time: 2021-09-28 15:12:58.307

Log type: error

Wrong method location: log4netwebapi Controllers. WeatherForecastController. Get (Log4NetWebAPI),

Wrong line number: 36 lines,

Error message: input string was not in a correct format (the format of the input string is incorrect.)

The following is a screenshot of the controller method

This is aboutASP.NET Core This is the end of the article on the global exception handling mechanism for the use of middlewareASP.NET Core For the content of global exception handling mechanism, please search the previous articles of developeppaer or continue to browse the relevant articles below. I hope you can support developeppaer in the future!

Recommended Today

Getting started with JDBC (I)

The first thing you need to do is to install it correctly. This includes the following steps: Install Java and JDBC on your computerJava database connection (JDBC) is a standard SQL (Structured Query Language) database access interface, which can provide unified access to a variety of relational databases. JDBC (Java database connection) also provides a […]