自定义 ocelot 中间件输出自定义错误信息
自定义 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 error
await 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 config
app.UseDownstreamContextMiddleware();
// This is registered to catch any global exceptions that are not handled
// It also sets the Request Id if anything is set globally
ocelotBuilder.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 中间件输出自定义错误信息的更多相关文章
- ASP.NET Core错误处理中间件[1]: 呈现错误信息
NuGet包"Microsoft.AspNetCore.Diagnostics"中提供了几个与异常处理相关的中间件.当ASP.NET Core应用在处理请求过程中出现错误时,我们可 ...
- 学习笔记6-Android查看应用输出的错误信息 如何部署应用到真实手机 发布软件
查看应用输出的错误信息 1. 通过LogCat窗口查看信息 右上角图标可以筛选不同级别的信息(比如info等). 右上角的+可以进行信息筛选 把应用部署到真实手机 1. 要把手机的 ...
- ORACLE输出详细错误信息错误行数
... COMMIT; --输出成功信息 DBMS_OUTPUT.PUT_LINE('RUN RESULT: SUCCESS'); EXCEPTION WHEN OTHERS THEN BEGIN R ...
- nginx自定义log_format以及输出自定义http头
官方文档地址: http://nginx.org/en/docs/http/ngx_http_log_module.html 一.log_format默认格式 首先Nginx默认的log_format ...
- C# 调用外部程序,并获取输出和错误信息
1. 同步模式 public void exec(string exePath, string parameters) { System.Diagnostics.ProcessStartInfo ps ...
- asp.net mvc输出自定义404等错误页面,非302跳转
朋友问到一个问题,如何输出自定义错误页面,不使用302跳转.当前页面地址不能改变. 还要执行一些代码等,生成一些错误信息,方便用户提交反馈. 500错误,mvc框架已经有现成解决方法: filte ...
- Spring Boot 如何自定义返回错误码错误信息
说明 在实际的开发过程中,很多时候要定义符合自己业务的错误码和错误信息,而不是统一的而不是统一的下面这种格式返回到调用端 INTERNAL_SERVER_ERROR(500, "Intern ...
- Java输出错误信息与调试信息
创建一个类,在该类的main()主方法中,使用System类中的out和err两个成员变量来完成调试与错误信息的输出. public class PrintErrorAndDebug { public ...
- PHP中的错误信息
PHP中的错误信息 php.ini中配置错误消息 在PHP4中,没有异常 Exception这个概念,只有 错误Error.我们可以通过修改php.ini 文件来配置用户端输出的错误信息. 在ph ...
随机推荐
- gitlab git仓库地址修改后更新方法
背景 由于gitlab地址修改后导致本地仓库的远程仓库失效 解决办法 直接修改本地的远程仓库地址 - 进入项目地址git remote -v 查看旧地址 - 更新指令 git remote set-u ...
- Array.apply(null, {length: 2}) 的理解
// apply 的第二参数通常是数组 但是也可以传递类数组对象{length: 2}console.log(Array.apply(null, {length: 2})) // [undefined ...
- 【JavaWeb】JSTL 标签库
JSTL 标签库 简介 JSTL(JSP Standard Tag Library),即 JSP 标准标签库.标签库是为了替换代码脚本,使得整个 jsp 页面变得更加简洁. JSTL 有五个功能不同的 ...
- MySQL select 子查询的使用
### 子查询 >where 这个值是计算出来的 >本质:`在 where 语句中嵌套一个子查询语句` ```sql /*============== 子查询 ============== ...
- 【Software Test】Introduction to Software Testing
Introduction to Software Testing 文章目录 Going to Learn --. Evolution of The Software Industry Errors, ...
- 代码审计 - BugkuCTF
extract变量覆盖: 相关函数: extract()函数:从数组中将变量导入到当前的符号表.把数组键名作为变量名,数组的键值作为变量值.但是当变量中有同名的元素时会默认覆盖掉之前的变量值. tri ...
- SDUST数据结构 - chap1 绪论
一.判断题: 二.选择题:
- 史上最全postgreSQL体系结构(转)
原文链接:https://cloud.tencent.com/developer/article/1469101 墨墨导读:本文主要从日志文件.参数文件.控制文件.数据文件.redo日志(WAL).后 ...
- dblink查找对应的目标端session
v$session试图中process字段代表的是客户端所在机器的进程号 例如我使用toad连接数据库,查询到的process即toad的进程号 SELECT process FROM V$SESSI ...
- Spring Initializr中生成的mvnw是干吗的?
当我们使用Spring Initializr来创建Spring Boot工程的时候,有没有发现在工程根目录下有两个名为mvnw的文件: 从命名.图标.扩展名来猜测,这两个文件的作用应该是一样的,只是c ...