Asp.net core中的面向切面编程3---异常处理

Asp.net core中的面向切面编程3---异常处理_第1张图片

public class CustomExceptionFilterAttribute : Attribute, IExceptionFilter //, IAsyncExceptionFilter
{

    private readonly IModelMetadataProvider _IModelMetadataProvider;
    public CustomExceptionFilterAttribute(IModelMetadataProvider modelMetadataProvider)
    { 
        this._IModelMetadataProvider = modelMetadataProvider;
    }

    /// 
    /// 当有异常发生的时候,就会触发到这里
    /// 
    /// 
    /// 
    public void OnException(ExceptionContext context)
    {
        if (context.ExceptionHandled == false)
        {
            //在这里就开始处理异常--还是要响应结果给客户端
            //1.页面展示
            //2.包装成一个JSON格式
            if (IsAjaxRequest(context.HttpContext.Request)) //判断是否是Ajax请求--JSON
            { 
                //JSON返回
                context.Result = new JsonResult(new
                {
                    Succeess = false,
                    Message = context.Exception.Message
                });
            }
            else
            {
                //返回页面
                ViewResult result = new ViewResult { ViewName = "~/Views/Shared/Error.cshtml" };
                result.ViewData = new ViewDataDictionary(_IModelMetadataProvider, context.ModelState);
                result.ViewData.Add("Exception", context.Exception);
                context.Result = result; //断路器---只要对Result赋值--就不继续往后了; 
            } 
            context.ExceptionHandled = true;//表示当前异常被处理过
        } 
    }


    / 
    / 当有异常发生的时候,就会触发到这里
    / 
    / 
    / 
    / 
    //public Task OnExceptionAsync(ExceptionContext context)
    //{
    //    throw new NotImplementedException();
    //}


    private bool IsAjaxRequest(HttpRequest request)
    {
        //HttpWebRequest httpWebRequest = null;
        //httpWebRequest.Headers.Add("X-Requested-With", "XMLHttpRequest"); 
        string header = request.Headers["X-Requested-With"];
        return "XMLHttpRequest".Equals(header);
    }
}

 使用

  [TypeFilter(typeof(CustomExceptionFilterAttribute))]
  public IActionResult Index7()
  {
      throw new Exception("其实没啥,就是想要异常一下~~");
  }

Asp.net core中的面向切面编程3---异常处理_第2张图片

  

 Asp.net core中的面向切面编程3---异常处理_第3张图片

#region 中间件处理异常
{
    ///如果Http请求中的Response中的状态不是200,就会进入Home/Error中;
    app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");//只要不是200 都能进来

    //下面这个是自己拼装一个Reponse 输出
    app.UseExceptionHandler(errorApp =>
    {
        errorApp.Run(async context =>
        {
            context.Response.StatusCode = 200;
            context.Response.ContentType = "text/html";
            await context.Response.WriteAsync("\r\n");
            await context.Response.WriteAsync("ERROR!

\r\n"); var exceptionHandlerPathFeature = context.Features.Get(); Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); Console.WriteLine($"{exceptionHandlerPathFeature?.Error.Message}"); Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); if (exceptionHandlerPathFeature?.Error is FileNotFoundException) { await context.Response.WriteAsync("File error thrown!

\r\n"); } await context.Response.WriteAsync("Home
\r\n"); await context.Response.WriteAsync("\r\n"); await context.Response.WriteAsync(new string(' ', 512)); // IE padding }); }); } #endregion

 

你可能感兴趣的:(asp.net,okhttp,后端)