catalogue
preface:
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 API
Projects, selecting.NET Core3.1
。
2. Create global exception filter
Create an exception filter in the controller namedExceptionFilter.cs
, filter inheritanceIExceptionFilter
Interface.
Note that I useefcore+sqlserver
, you can use it according to your actual situationORM
And 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 filterIExceptionFilter
Interface.
IExceptionFilter
Interface will require implementationOnException
Method, which will be triggered when an uncaught exception occurs in the system.
Onexception method has aExceptionContext
Exception context, which contains specific exception information,HttpContext
andmvc
Routing 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))
{
}
}
#endregion
#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())
{
ctx.Add(md);
ctx.SaveChanges();
}
#endregion
//The following is the content prompt displayed on your return page, which is omitted below
}
}
}
3. Dependency injection global exception handling mechanism
stayStartup.cs
The global exception handling mechanism we just created is injected into the middleware and put into theConfigureServices
Method.
//Add global exception handling mechanism
services.AddMvc(option => {
option.Filters.Add<ExceptionFilter>();
});
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//Add global exception handling mechanism
services.AddMvc(option => {
option.Filters.Add<ExceptionFilter>();
});
}
4. Test the global exception handling mechanism
“Willstring
String 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!