ASP. NET sample code for logging errors through interceptors

  • 2021-11-29 06:41:35
  • OfStack

Preface to the table of contents Interceptor code actual combat

Preface

Mainly record 1 under the implementation of error log interception, you can control the information returned in the interceptor, and return the error information to the request end after processing.

Interceptor

Interceptors are also called filters.

asp. net mvc itself comes with three kinds of interceptors: Action interceptor, Result interceptor and Exception interceptor. Common interceptors in applications are log interceptor (Action interceptor) and exception handling interceptor (Exception interceptor).

In java, spring and mvc, interceptors are also commonly used to do things that do not interfere with business logic, such as implementing HandlerInterceptor interfaces.

Interceptor is an application of AOP (section-oriented programming).

Problems to be solved by interceptors:

1. Code reuse. Interceptors can be reused
2. Job list 1. For example, chefs are only responsible for cooking, regardless of washing vegetables in the early stage and delivering vegetables in the follow-up. If the food goes bad, someone will deal with it when they shout directly.

This time we use it to log errors

Code practice

Interceptor


    /// <summary>
    ///  Interface exception catch filter 
    /// </summary>
    [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
    public class ApiErrorHandleAttribute : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnException(actionExecutedContext);
            actionExecutedContext.Response = GetResponse(actionExecutedContext);
        }

        /// <summary>
        ///  Response method after catching exception 
        /// </summary>
        private HttpResponseMessage GetResponse(HttpActionExecutedContext actionExecutedContext)
        {
            var requesthost = actionExecutedContext.ActionContext.Request.RequestUri.ToString();// The address of the current request, including ip Add interface address 
            var method = actionExecutedContext.ActionContext.Request.Method.ToString();// The current request is POST/GET/PUT/DELETE  ... 
            var controller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerType.FullName;// The current requested controller is located in the full path: xxx.WebAPI.Controllers.xxxController
            var action = actionExecutedContext.ActionContext.ActionDescriptor.ActionName; // The currently requested method 
            var paramters = actionExecutedContext.ActionContext.ActionArguments; // Gets the parameters of the current request 
            var ip = HttpContext.Current.Request.UserHostAddress;
           
            LogHelper.Error($" Error message: URL:{actionExecutedContext.Request.RequestUri},-- Parameter information: {paramters.ToJson()},--actionExecutedContext.Exception:{actionExecutedContext.Exception.ToJson()}");
            var response = new { code = 506, message = $"{actionExecutedContext.Exception.Message},URL:{actionExecutedContext.Request.RequestUri}", ex = actionExecutedContext.Exception };
           
            return JsonHelper.ToHttpResponseMessage(response);
        }

    }

Tool class method


    public static class JsonHelper
    {
        /// <summary>
        ///  Convert to json Format HttpResponseMessage
        /// </summary>
        public static HttpResponseMessage ToHttpResponseMessage(object obj)
        {
            string str;
            if (obj is string || obj is char)
            {
                str = obj.ToString();
            }
            else
            {
                str = obj.ToJson();
            }
            var result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") };
            return result;
        }

        /// <summary>
        ///  Convert to json String, default time format 
        /// </summary>
        /// <param name="obj"> Object to be converted </param>
        /// <returns>json String </returns>
        public static string ToJson(this object obj)
        {
            return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, DateFormatString = "yyyy-MM-dd HH:mm:ss" });
        }
    }

These are the details of the sample code for ASP. NET logging errors through interceptors. For more information about ASP. NET logging errors, please pay attention to other related articles on this site!


Related articles: