自定义 ocelot 中间件输出自定义错误信息

Intro

ocelot 中默认的 Response 中间件在出错的时候只会设置 StatusCode 没有具体的信息,想要展示自己定义的错误信息的时候就需要做一些自定义了,对 ocelot 中的 Response 中间件做了一些小改动,实现了输出自定义错误信息的功能。

Implement

实现起来其实也很简单,原来的有错误的时候,只设置了 Response 的 StatusCode,我们只需要加一下输出错误信息就可以了,错误信息的格式完全可以自定义,实现代码如下:

public class CustomResponseMiddleware : Ocelot.Middleware.OcelotMiddleware
{private readonly RequestDelegate _next;private readonly IHttpResponder _responder;private readonly IErrorsToHttpStatusCodeMapper _codeMapper;public CustomResponseMiddleware(RequestDelegate next,IHttpResponder responder,IErrorsToHttpStatusCodeMapper codeMapper,IOcelotLoggerFactory loggerFactory): base(loggerFactory.CreateLogger<UrlBasedAuthenticationMiddleware>()){_next = next;_responder = responder;_codeMapper = codeMapper;}public async Task Invoke(HttpContext httpContext){await _next.Invoke(httpContext);if (httpContext.Response.HasStarted)return;var errors = httpContext.Items.Errors();if (errors.Count > 0){Logger.LogWarning($"{errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{httpContext.Request.Path}, request method: {httpContext.Request.Method}");var statusCode = _codeMapper.Map(errors);var error = string.Join(",", errors.Select(x => x.Message));httpContext.Response.StatusCode = statusCode;// output errorawait httpContext.Response.WriteAsync(error);}else{Logger.LogDebug("no pipeline errors, setting and returning completed response");var downstreamResponse = httpContext.Items.DownstreamResponse();await _responder.SetResponseOnHttpContext(httpContext, downstreamResponse);}}
}

相比之前的中间件,主要变化就是对于 Error 的处理,感觉这里 ocelot 可以抽象一下,增加一个接口 ErrorResponser 之类的,现在的 responder 没有直接把错误信息直接传进去造成一些不变,加一个 ErrorResponder 只处理 Error 相关的逻辑,把错误信息直接传进去,这样用户也就可以更为灵活的注册自己的服务来无侵入的修改发生错误时的行为

Sample

要使用这个中间件,就要自己定义 ocelot 中间件的配置,把默认的 Response 中间件替换成自己的中间件即可,示例如下:

app.UseOcelot((ocelotBuilder, ocelotConfiguration) =>
{// this sets up the downstream context and gets the configapp.UseDownstreamContextMiddleware();// This is registered to catch any global exceptions that are not handled// It also sets the Request Id if anything is set globallyocelotBuilder.UseExceptionHandlerMiddleware();// This is registered first so it can catch any errors and issue an appropriate response//ocelotBuilder.UseResponderMiddleware();ocelotBuilder.UseMiddleware<CustomResponseMiddleware>();ocelotBuilder.UseDownstreamRouteFinderMiddleware();ocelotBuilder.UseMultiplexingMiddleware();ocelotBuilder.UseDownstreamRequestInitialiser();ocelotBuilder.UseRequestIdMiddleware();// 自定义中间件,模拟没有权限的情况ocelotBuilder.Use((ctx, next) =>{ctx.Items.SetError(new UnauthorizedError("No permission"));return Task.CompletedTask;});//ocelotBuilder.UseMiddleware<UrlBasedAuthenticationMiddleware>();ocelotBuilder.UseLoadBalancingMiddleware();ocelotBuilder.UseDownstreamUrlCreatorMiddleware();ocelotBuilder.UseHttpRequesterMiddleware();
}).Wait();

除了上面的 Response 中间件,为了测试方便,我还加了一个中间件,直接设置了一个 Error 来方便测试,随便访问一个 Path 来测试一下是不是会有错误信息,可以看到正如预期的结果一样,输出了我们自定义的错误信息

More

完整示例可以从 Github 上获取 https://github.com/WeihanLi/AspNetCorePlayground/tree/master/OcelotDemo

Reference

  • https://github.com/WeihanLi/AspNetCorePlayground/blob/master/OcelotDemo/OcelotMiddleware/CustomResponseMiddleware.cs

  • https://github.com/WeihanLi/AspNetCorePlayground/tree/master/OcelotDemo

  • https://github.com/ThreeMammals/Ocelot/blob/17.0.0/src/Ocelot/Responder/HttpContextResponder.cs

  • https://github.com/ThreeMammals/Ocelot/blob/17.0.0/src/Ocelot/Responder/Middleware/ResponderMiddleware.cs

自定义 ocelot 中间件输出自定义错误信息相关推荐

  1. linux输出文件没有找到,Linux环境下标准输入、输出、错误信息详解

    Linux环境下标准输入.输出.错误信息详解 下面我们介绍在Linux环境下标准输入.输出.错误设备.标准输入设备代号为0, 用来显示输入信息,标准输出设备代号为1,用来显示正常信息,标准错误设备代号 ...

  2. Android学习笔记07---查看Android虚拟机输出的错误信息与如何部署应用到自己的真实手机

    Android学习笔记07---查看Android虚拟机输出的错误信息

  3. Python使用try...except...输出详细错误信息(比如报错具体位置在第几行)

     代码详情如下: # Python使用try...except...输出详细错误信息(比如报错具体位置在第几行)import sys import tracebacktry:print(1/1)pri ...

  4. 设置调试PHP,debug php输出所有错误信息

    2019独角兽企业重金招聘Python工程师标准>>> 任意环境下调试php,debug php 在不管php.ini配置的情况下开启php调试,php debug. 在你需要调试的 ...

  5. linux输出和错误信息文件,Log4j配置将错误信息输出到指定文件中[linux tomcat]

    在使用log4j的时候,我们常常需要将错误信息输出到指定路径的文件中 以便于以后查询出错信息 在网上搜了很多资料都是写的windows下的输出方法,而且很多都是不负责任的直接E:// 很多时候我们希望 ...

  6. 让SharePoint站点输出详细错误信息[转]

    转自:http://blog.csdn.net/jackjoy/archive/2007/07/31/1719012.aspx 很显然,这样的错误提示除了会让人抓狂之外对解决问题没有任何帮助,弄过AS ...

  7. java异常日志不要只打一半,要输出全部错误信息

    //错误 try{ }catch(Exception e){log.error("你的程序有异常啦"); } 异常e都没有打印出来,所以压根不知道出了什么类型的异常 //错误 tr ...

  8. 让CMD窗口显示中文[JAVAC输出中文错误信息乱码的解决]

    临时解决方案: 在 CMD 中运行 chcp 936. 永久解决方案: 打开不正常的 CMD 或命令提示符窗口后,单击窗口左上角的图标,选择弹出的菜单中的"默认值",打开如下图的对 ...

  9. java异常自定义返回信息,Spring Boot 如何自定义返回错误码错误信息

    说明 在实际的开发过程中,很多时候要定义符合自己业务的错误码和错误信息,而不是统一的而不是统一的下面这种格式返回到调用端 INTERNAL_SERVER_ERROR(500, "Intern ...

最新文章

  1. AI一分钟|Uber撤裁100名无人车操作员;京东金融将融资130亿人民币
  2. Ueditor编辑旧文章,从数据库中取出要修改的内容
  3. 完善Linux/UNIX审计 将每个shell命令记入日志
  4. CSS 布局与“仓库管理”的关系
  5. Leaflet文档阅读笔记- Showing video files解析
  6. Spring和SpringMVC父子容器关系初窥
  7. a+ open python_python编程之文件操作
  8. 计算机如何取消自动关机,怎么解除电脑自动关机
  9. 【jzoj2173】【DFS】无根树
  10. 第六节 ftpserver的安装与配置(Windows)
  11. 一文学会Webpack实用功能|加载器篇
  12. 查找微信公众号服务器,墨涩网 - 免插件实现微信公众号搜索连接wordpress网站文章——墨涩网...
  13. java excel合并,Java Excel合并工具
  14. 时间的加减法怎么用计算机算,时间加减计算器
  15. mathtype向上取整函数
  16. 什么是程序员的核心竞争力?
  17. 【扒开】关于赢驴准心劫持浏览器首页的病毒类行径
  18. 圆柱体积怎么算立方公式_立方计算公式,圆形怎么算立方。
  19. 广工计算机学院绩点,广工平均学分绩点计算器的教程
  20. PAT 乙级 1036  跟奥巴马一起编程

热门文章

  1. python input 文件名_Python播放音频与录音
  2. 确定最佳聚类数matlab代码_详解DBSCAN聚类
  3. 中文分词入门之字标注法4
  4. [转] Node.js的线程和进程
  5. 看出每个应用程序最高可用内存是多少
  6. JAVA学习博客---2015.5
  7. Teams Bot开发系列:Bot验证
  8. Microsoft Teams:团队Owner离开公司后,我们该怎么做?
  9. 如何在Windows 8中更改登录屏幕的颜色
  10. 跟风学Docker之四:Docker网络解决方案