Location>code7788 >text

(Series VI) .net8 global exception catching mechanism

Popularity:907 ℃/2024-10-12 16:31:47

clarification

This article is part of the OverallAuth 2.0 series of articles, which is updated weekly with an article in the series (Complete System Development from 0 to 1).

I will try to be very detailed in this system article, so that it can be understood by novice and veteran alike.

DESCRIPTION: OverallAuth 2.0 is a simple, easy to understand and powerful Permissions + Visual Process Management system.

Friendly reminder: this article is part of a series of articles, before reading that article, it is recommended to read the previous articles to better understand the structure of the project.

If you are interested, please follow me (*^▽^*).

Follow me. Beat me if you can't learn.

Why use global exception catching?

Global exception catching is essential for a system, not only to streamline exception information back to the user, but also to help programmers reduce the time it takes to resolve problems, as well as to record information about exceptions that occur anywhere in the system.

Are you still suffering from the following?

Are you still struggling with how to record system exception logs?

Are you still struggling with the location and message of the system error report?

Are you also adding logging operations at each interface?

If you have, then this post is just the right solution to your dilemma.

What is the global exception catching mechanism?

Global Exception Catching, as the name suggests, means that the system will be caught no matter where an error occurs in that location so that it can be handled.

Creating Interface Return Models

Creates an interface return model:

Its main role is to push the data and information returned by the interface to the front-end.

 /// <summary>
 /// The interface returns the entity model
/// </summary>
 public class ReceiveStatus
 {
     /// <summary>
     /// encodings
/// </summary>
     public CodeStatuEnum code { get; set; }

     /// <summary>
     /// text
/// </summary>
     public string msg { get; set; }

     /// <summary>
     /// success or failure
/// </summary>
     public bool success { get; set; }

     /// <summary>
     /// constructor
/// </summary>
     public ReceiveStatus()
     {
         code = ;
         success = true;
         msg = "The operation was successful.";
     }
 }
 /// <summary>
 /// The interface returns the result set
/// </summary>
 /// <typeparam name="T"></typeparam>
 public class ReceiveStatus<T> : ReceiveStatus
 {
     /// <summary>
     /// digital
/// </summary>
     public List<T> data { get; set; }

     /// <summary>
     /// total number
/// </summary>
     public int total { get; set; }
 }
The enumeration values are as follows
 /// <summary>
 /// Code State Enumeration
/// </summary>
 public enum CodeStatuEnum
 {
     /// <summary>
     /// The operation was successful.
/// </summary>
     Successful = 200,

     /// <summary>
     ///  warnings
/// </summary>
     Warning = 99991,

     /// <summary>
     /// The operation triggers an error.
/// </summary>
     Error = 99992
 }

After creating the interface return model, we create an exception helper class, its main purpose, to distinguish between [system exceptions] or user-defined [business exceptions].

/// <summary>
/// Exception Help Class
/// </summary>
public class ExceptionHelper
{
    /// <summary>
    /// Custom exceptions (which are written to the error log table)
/// </summary>
    /// <param name="msg"></param>
    public static void ThrowBusinessException(string msg)
    {
        throw new Exception(msg);
    }

    /// <summary>
    /// Customized business exceptions (not written to error log table)
/// </summary>
    /// <param name="msg">Information Information</param>
    /// <param name="codeStatu">abnormal state</param>
    /// <returns>Returns the result set</returns>
    public static ReceiveStatus CustomException(string msg, CodeStatuEnum codeStatu = )
    {
        ReceiveStatus receiveStatus = new();
         = codeStatu;
         = msg;
         = false;
        return receiveStatus;
    }

}

/// <summary>
/// Exception helper class (return data)
/// </summary>
/// <typeparam name="T"></typeparam>
public class ExceptionHelper<T> : ExceptionHelper
{
    /// <summary>
    /// Customized business exceptions (not written to error log table)
/// </summary>
    /// <param name="msg">Information Information</param>
    /// <param name="codeStatu">abnormal state</param>
    /// <returns>Returns the result set</returns>
    public static ReceiveStatus<T> CustomExceptionData(string msg, CodeStatuEnum codeStatu = )
    {
        ReceiveStatus<T> receiveStatus = new();
         = codeStatu;
         = msg;
         = false;
         = new <T>();
        return receiveStatus;
    }
}

Creating a global exception catching middleware

Create a class in the wenApi starter project:

Its main role is to catch the code in the system where the exception occurs and record the exception log.

It needs to inherit an interface: IAsyncExceptionFilter

/// <summary>
/// Global Exception Catching Middleware
/// </summary>
public class ExceptionPlugIn : IAsyncExceptionFilter
{
    /// <summary>
    /// Global Exception Catching Interface
/// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task OnExceptionAsync(ExceptionContext context)
    {
        //Exception information
        Exception ex = ;

        //abnormal position
        var DisplayName = ;

        //Exception line number
        int lineNumber = 0;
        const string lineSearch = ":line ";
        var index = (lineSearch);
        if (index != -1)
        {
            var lineNumberText = (index + );
            lineNumber = Convert.ToInt32((0, ("\r\n")));
        }

        // Handle the exception if it is not handled
        if ( == false)
        {
            string exceptionMsg = "Incorrect location:" + DisplayName + "\r\n" + "Error line number:" + lineNumber + "\r\n" + "Error message:" + ;
            // Defining the return type
            var result = new ReceiveStatus<string>
            {
                code = ,
                msg = "Error message:" + exceptionMsg,
                success = false,
            };
             = new ContentResult
            {
                // The return status code is set to 200, indicating that the
                StatusCode = StatusCodes.Status500InternalServerError,
                // Setting the return format
                ContentType = "application/json;charset=utf-8",
                Content = (result)
            };
            //log

        }
        // Set to true to indicate that the exception has been handled
         = true;
        return ;
    }
}

You can add code for logging, exception type, exception analysis, etc. to the OnExceptionAsync method.

Add to service

Once we have written the exception catching mechanism, we need to add the class to the service

//Customizing global exception handling
(a =>
{
    (typeof(ExceptionPlugIn));
});

Testing the global exception catching mechanism

Adding an Exception Test Interface

operational test

Above is the global exception catching mechanism, if you are interested, you can download the project and modify it.

Source code address: /yangguangchenjie/overall-auth2.0-web-api

Preview at http://139.155.137.144:8880/swagger/

Help me Star, please.

If you are interested, please pay attention to my weibo public number (*^▽^*).

Follow me: a full-stack multi-terminal treasure blogger, regularly sharing technical articles, irregularly sharing open source projects. Follow me to bring you to know a different program world!