Home  >  Article  >  Backend Development  >  ExceptionFilter filter in asp.net

ExceptionFilter filter in asp.net

巴扎黑
巴扎黑Original
2017-09-01 15:07:371988browse

This article mainly introduces the ExceptionFilter filter of the asp.net core MVC global filter in detail. It has a certain reference value. Interested friends can refer to it.

This series of classes will Will explain the use of the built-in global filter in asp.net core MVC, which will be divided into the following chapters

 asp.net core MVC filter ExceptionFilter filter (1)

 asp.net core MVC filter's ActionFilter filter (2)

 asp.net core MVC filter's ResultFilter filter (3)

 asp.net core MVC filter's ResourceFilter filter (4) )

 AuthorizationFilter filter of asp.net core MVC filter (5)

Introduction

Exception filter, as the name suggests, is when the program occurs Filter to use on exceptions. Used to handle uncaught exceptions in the system.

Implementing a custom exception filter

Customizing a global exception filter requires implementing the IExceptionFilter interface


##

public class HttpGlobalExceptionFilter : IExceptionFilter
  {
    public void OnException(ExceptionContext context)
    {
      throw new NotImplementedException();
    }
  }

The IExceptionFilter interface will require Implement the OnException method, which will be triggered when an uncaught exception occurs in the system. The OnException method has an ExceptionContext exception context, which contains specific exception information, HttpContext and mvc routing information. Once an uncaught exception occurs in the system, a common approach is to use a logging tool to record the detailed information of the exception to facilitate correction and debugging. Below is the implementation of logging.


  /// <summary>
  /// 全局异常过滤器
  /// </summary>
  public class HttpGlobalExceptionFilter : IExceptionFilter
  {
    readonly ILoggerFactory _loggerFactory;
    readonly IHostingEnvironment _env;

    public HttpGlobalExceptionFilter(ILoggerFactory loggerFactory, IHostingEnvironment env)
    {
      _loggerFactory = loggerFactory;
      _env = env;
    }

    public void OnException(ExceptionContext context)
    {
      var logger = _loggerFactory.CreateLogger(context.Exception.TargetSite.ReflectedType);

        logger.LogError(new EventId(context.Exception.HResult),
        context.Exception,
        context.Exception.Message);

        var json = new ErrorResponse("未知错误,请重试");

        if (_env.IsDevelopment()) json.DeveloperMessage = context.Exception;

        context.Result = new ApplicationErrorResult(json);
        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

      context.ExceptionHandled = true;
    }

public class ApplicationErrorResult : ObjectResult
  {
    public ApplicationErrorResult(object value) : base(value)
    {
      StatusCode = (int)HttpStatusCode.InternalServerError;
    }
  }

public class ErrorResponse
  {
    public ErrorResponse(string msg)
    {
      Message = msg;
    }
    public string Message { get; set; }
    public object DeveloperMessage { get; set; }
  }

Register global filter

The filter has been written, and then it needs to be registered in asp.net core MVC. Find the Startup.cs file in the system root directory and modify the ConfigureServices method as follows


 services.AddMvc(options =>
      {
        options.Filters.Add<HttpGlobalExceptionFilter>();
      });

Test

Throw an exception in the request

The log correctly captures the exception information

The browser returns a 500 error and returns a customized error message.

The above is the detailed content of ExceptionFilter filter in asp.net. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn