当前位置: 移动技术网 > IT编程>开发语言>.net > ASP.NET Core应用错误处理之ExceptionHandlerMiddleware中间件呈现“定制化错误页面”

ASP.NET Core应用错误处理之ExceptionHandlerMiddleware中间件呈现“定制化错误页面”

2019年01月07日  | 移动技术网IT编程  | 我要评论

查发网,星野琉璃h,闪电霹雳车

前言

developerexceptionpagemiddleware中间件利用呈现出来的错误页面实现抛出异常和当前请求的详细信息以辅助开发人员更好地进行纠错诊断工作,而exceptionhandlermiddleware中间件则是面向最终用户的,我们可以利用它来显示一个友好的定制化的错误页面。按照惯例,我们还是先来看看exceptionhandlermiddleware的类型定义。

 public class exceptionhandlermiddleware
 { 
 public exceptionhandlermiddleware(requestdelegate next, iloggerfactory loggerfactory, ioptions<exceptionhandleroptions> options, diagnosticsource diagnosticsource); 
 public task invoke(httpcontext context);
 }
 
 public class exceptionhandleroptions
 {
 public requestdelegate exceptionhandler { get; set; }
 public pathstring  exceptionhandlingpath { get; set; }
 }

与developerexceptionpagemiddleware类似,我们在创建一个exceptionhandlermiddleware对象的时候同样需要提供一个携带配置选项的对象,从上面的代码可以看出这是一个exceptionhandleroptions。具体来说,一个exceptionhandleroptions对象通过其exceptionhandler属性提供了一个最终用来处理请求的requestdelegate对象。如果希望发生异常后自动重定向到某个指定的路径,我们可以利用exceptionhandleroptions对象的exceptionhandlingpath属性来指定这个路径。我们一般会调用applicationbuilder的扩展方法useexceptionhandler来注册exceptionhandlermiddleware中间件,这些重载的useexceptionhandler方法会采用如下的方式完整中间件的注册工作。

 public static class exceptionhandlerextensions
 {
 public static iapplicationbuilder useexceptionhandler(this iapplicationbuilder app)=> app.usemiddleware<exceptionhandlermiddleware>();
 
 public static iapplicationbuilder useexceptionhandler(this iapplicationbuilder app, exceptionhandleroptions options) 
 => app.usemiddleware<exceptionhandlermiddleware>(options.create(options));
 
 public static iapplicationbuilder useexceptionhandler(this iapplicationbuilder app, string errorhandlingpath)
 { 
  return app.useexceptionhandler(new  {
  exceptionhandlingpath = new pathstring(errorhandlingpath)
  });
 }
 
 public static iapplicationbuilder useexceptionhandler(this iapplicationbuilder app, action<iapplicationbuilder> configure)
 {
  iapplicationbuilder newbuilder = app.new();
  configure(newbuilder);
 
  return app.useexceptionhandler(new exceptionhandleroptions
  {
  exceptionhandler = newbuilder.build()
  });
 } 
 }

一、异常处理器

exceptionhandlermiddleware中间件处理请求的本质就是在后续请求处理过程中出现异常的情况下采用注册的异常处理器来处理并响应请求,这个异常处理器就是我们再熟悉不过的requestdelegate对象。该中间件采用的请求处理逻辑大体上可以通过如下所示的这段代码来体现。

 public class exceptionhandlermiddleware
 {
 private requestdelegate  _next;
 private exceptionhandleroptions _options;
 
 public exceptionhandlermiddleware(requestdelegate next, ioptions<exceptionhandleroptions> options,…)
 {
  _next  = next;
  _options = options.value;
  …
 }
 
 public async task invoke(httpcontext context)
 {
  try
  {
  await _next(context);
  }
  catch 
  {
  context.response.statuscode = 500;
  context.response.clear();
  if (_options.exceptionhandlingpath.hasvalue)
  {
   context.request.path = _options.exceptionhandlingpath;
  }
  requestdelegate handler = _options.exceptionhandler ?? _next;
  await handler(context);
  }
 }
 }

如上面的代码片段所示,如果后续的请求处理过程中出现异常,exceptionhandlermiddleware中间件会利用一个作为异常处理器的requestdelegate对象来完成最终的请求处理工作。如果在创建exceptionhandlermiddleware时提供的exceptionhandleroptions携带着这么一个requestdelegate对象,那么它将作为最终使用的异常处理器,否则作为异常处理器的实际上就是后续的中间件。换句话说,如果我们没有通过exceptionhandleroptions显式指定一个异常处理器,exceptionhandlermiddleware中间件会在后续管道处理请求抛出异常的情况下将请求再次传递给后续管道。

当exceptionhandlermiddleware最终利用异常处理器来处理请求之前,它会对请求做一些前置处理工作,比如它会将响应状态码设置为500,比如清空当前所有响应内容等。如果我们利用exceptionhandleroptions的exceptionhandlingpath属性设置了一个重定向路径,它会将该路径设置为当前请求的路径。除了这些,exceptionhandlermiddleware中间件实际上做了一些没有反应在上面这段代码片段中的工作。

二、异常的传递与请求路径的恢复

由于exceptionhandlermiddleware中间件总会利用一个作为异常处理器的requestdelegate对象来完成最终的异常处理工作,为了让后者能够得到抛出的异常,该中间件应该采用某种方式将异常传递给它。除此之外,由于exceptionhandlermiddleware中间件会改变当前请求的路径,当整个请求处理完成之后,它必须将请求路径恢复成原始的状态,否则前置的中间件就无法获取到正确的请求路径。

请求处理过程中抛出的异常和原始请求路径的恢复是通过相应的特性完成的。具体来说,传递这两者的特性分别叫做exceptionhandlerfeature和exceptionhandlerpathfeature,对应的接口分别为iexceptionhandlerfeature和iexceptionhandlerpathfeature,如下面的代码片段所示,后者继承前者。默认使用的exceptionhandlerfeature实现了这两个接口。

 public interface iexceptionhandlerfeature
 {
 exception error { get; }
 }
 
 public interface iexceptionhandlerpathfeature : iexceptionhandlerfeature
 {
 string path { get; }
 }
 
 public class exceptionhandlerfeature : iexceptionhandlerpathfeature, 
 {
 public exception error { get; set; }
 public string path { get; set; }
 }

当exceptionhandlermiddleware中间件将代码当前请求的httpcontext传递给请求处理器之前,它会按照如下所示的方式根据抛出的异常的原始的请求路径创建一个exceptionhandlerfeature对象,该对象最终被添加到httpcontext之上。当整个请求处理流程完全结束之后,exceptionhandlermiddleware中间件会借助这个特性得到原始的请求路径,并将其重新应用到当前请求上下文上。

 public class exceptionhandlermiddleware
 {
  ...
  public async task invoke(httpcontext context)
  {
   try
   {
    await _next(context);
   }
   catch(exception ex)
   {
    context.response.statuscode = 500;
 
    var feature = new exceptionhandlerfeature()
    {
     error = ex,
     path = context.request.path,
    };
    context.features.set<iexceptionhandlerfeature>(feature);
    context.features.set<iexceptionhandlerpathfeature>(feature);
 
    if (_options.exceptionhandlingpath.hasvalue)
    {
     context.request.path = _options.exceptionhandlingpath;
    }
    requestdelegate handler = _options.exceptionhandler ?? _next;
 
    try
    {
     await handler(context);
    }
    finally
    {
     context.request.path = originalpath;
    }
   }
  }
 }

在具体进行异常处理的时候,我们可以从当前httpcontext中提取这个exceptionhandlerfeature对象,进而获取抛出的异常和原始的请求路径。如下面的代码所示,我们利用handleerror方法来呈现一个定制的错误页面。在这个方法中,我们正式借助于这个exceptionhandlerfeature特性得到抛出的异常,并将它的类型、消息以及堆栈追踪显示出来。

 public class program
 {
  public static void main()
  {
   new webhostbuilder()
    .usekestrel()
    .configureservices(svcs=>svcs.addrouting())
    .configure(app => app
     .useexceptionhandler("/error")
     .userouter(builder=>builder.maproute("error", handleerror))
     .run(context=> task.fromexception(new invalidoperationexception("manually thrown exception"))))
    .build()
    .run();
  }
 
  private async static task handleerror(httpcontext context)
  {
   context.response.contenttype = "text/html";
   exception ex = context.features.get<iexceptionhandlerpathfeature>().error;
 
   await context.response.writeasync("<html><head><title>error</title></head><body>");
   await context.response.writeasync($"<h3>{ex.message}</h3>");
   await context.response.writeasync($"<p>type: {ex.gettype().fullname}");
   await context.response.writeasync($"<p>stacktrace: {ex.stacktrace}");
   await context.response.writeasync("</body></html>");
  }

在上面这个应用中,我们注册了一个模板为“error”的路由指向这个handleerror方法。对于通过调用扩展方法useexceptionhandler注册的exceptionhandlermiddleware来说,我们将该路径设置为异常处理路径。那么对于任意从浏览器发出的请求,都会得到如下图所示的错误页面。

三、清除缓存

对于一个用于获取资源的get请求来说,如果请求目标是一个相对稳定的资源,我们可以采用客户端缓存的方式避免相同资源的频繁获取和传输。对于作为资源提供者的web应用来说,当它在处理请求的时候,除了将目标资源作为响应的主体内容之外,它还需要设置用于控制缓存的相关响应报头。由于缓存在大部分情况下只适用于成功的响应,如果服务端在处理请求过程中出现异常,之前设置的缓存报头是不应该出现在响应报文中。对于exceptionhandlermiddleware中间件来说,清楚缓存报头也是它负责的一项重要工作。

我们同样可以通过一个简单的实例来演示exceptionhandlermiddleware中间件针对缓存响应报头的清除。在如下这个应用中,我们将针对请求的处理实现在invoke方法中,它有50%的可能会抛出异常。不论是返回正常的响应内容还是抛出异常,这个方法都会先设置一个“cache-control”的响应报头,并将缓存时间设置为1个小时(“cache-control: max-age=3600”)。

 public class program
 {
  public static void main()
  {
   new webhostbuilder()
    .usekestrel()
    .configureservices(svcs => svcs.addrouting())
    .configure(app => app
     .useexceptionhandler(builder => builder.run(async context => await context.response.writeasync("error occurred!")))
     .run(invoke))
    .build()
    .run();
  }
 
  private static random _random = new random();
  private async static task invoke(httpcontext context)
  {
   context.response.gettypedheaders().cachecontrol = new cachecontrolheadervalue
   {
    maxage = timespan.fromhours(1)
   };
 
   if (_random.next() % 2 == 0)
   {
    throw new invalidoperationexception("manually thrown exception...");
   }
   await context.response.writeasync("succeed...");
  }
 }

通过调用扩展方法 useexceptionhandler注册的exceptionhandlermiddleware中间件在处理异常时会响应一个内容为“error occurred!”的字符串。如下所示的两个响应报文分别对应于正常响应和抛出异常的情况,我们会发现程序中设置的缓存报头“cache-control: max-age=3600”只会出现在状态码为“200 ok”的响应中。至于状态码为“500 internal server error”的响应中,则会出现三个与缓存相关的报头,它们的目的都会为了禁止缓存(或者指示缓存过期)。

 http/1.1 200 ok
 date: sat, 17 dec 2016 14:39:02 gmt
 server: kestrel
 cache-control: max-age=3600
 content-length: 10
 
 succeed...
 
 
 http/1.1 500 internal server error
 date: sat, 17 dec 2016 14:38:39 gmt
 server: kestrel
 cache-control: no-cache
 pragma: no-cache
 expires: -1
 content-length: 15
 
 error occurred!

exceptionhandlermiddleware中间件针对缓存响应报头的清除体现在如下所示的代码片段中。我们可以看出它通过调用httpresponse的onstarting方法注册了一个回调(clearcacheheaders),上述的这三个缓存报头在这个回调中设置的。除此之外,我们还看到这个回调方法还会清除etag报头,这也很好理解:由于目标资源没有得到正常的响应,表示资源“签名”的etag报头自然不应该出现在响应报文中。

 public class exceptionhandlermiddleware
 {
  ...
  public async task invoke(httpcontext context)
  {
   try
   {
    await _next(context);
   }
   catch (exception ex)
   {
    …
    context.response.onstarting(clearcacheheaders, context.response);
    requestdelegate handler = _options.exceptionhandler ?? _next;
    await handler(context);
   }
  }
 
  private task clearcacheheaders(object state)
  {
   var response = (httpresponse)state;
   response.headers[headernames.cachecontrol]  = "no-cache";
   response.headers[headernames.pragma]   = "no-cache";
   response.headers[headernames.expires]   = "-1";
   response.headers.remove(headernames.etag);
   return task.completedtask;
  }
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网