自定义 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 ...
随机推荐
- 【函数分享】每日PHP函数分享(2021-1-12)
str_pad() 使用另一个字符串填充字符串为指定长度 . string str_pad ( string $input, int $pad_length[, string $pad_string= ...
- WPF + RDLC + 动态生成列 + 表头合并
如下,评论超过20条,马上发代码*(੭*ˊᵕˋ)੭*ଘ,效果如下: 代码逻辑简单. WPF使用RDLC需要使用如下DLL 新建WPF 窗体,黏贴下大概如下 <Window xmlns:rv=&q ...
- Docusaurus2 快速建站,发布 GitHub Pages
Docusaurus2 可快速搭建文档.博客.官网等网站,并发布到 GitHub Pages, Serverless 等. 我们只需 Markdown 写写内容就行,也可直接编写 React 组件嵌入 ...
- 【Flutter】容器类组件之Container容器
前言 Container是一个组合类容器,它本身不对应具体的RenderObject,它是DecoratedBox.ConstrainedBox.Transform.Padding.Align等组件组 ...
- 【Flutter】容器类组件之装饰容器
前言 DecoratedBox可以在其子组件绘制前后绘制一些装饰,例如背景,边框,渐变等. 接口描述 const DecoratedBox({ Key key, // 代表要绘制的装饰 @requir ...
- 🎉 Element UI for Vue 3.0 来了!
第一个使用 TypeScript + Vue 3.0 Composition API 重构的组件库 Element Plus 发布了 ~ 2016 年 3 月 13 日 Element 悄然诞生,经历 ...
- ctfhub技能树—信息泄露—git泄露—index
打开靶机 查看页面信息 使用dirsearch进行扫描 使用githack工具处理git泄露情况 使用git log命令查看历史记录 与 add flag 9b5b58-- 这次提交进行比对 即可拿到 ...
- bean与map之间的转化
import java.util.HashMap; import java.util.Map; import org.apache.commons.beanutils.BeanUtils; impor ...
- 1V升3V芯片,1V升3.3V芯片,大电流的,低功耗
一般来说,1V的电压实在很低了,即使是干电池的话,再1V时,也是基本属于没电状态了.还有一种是干电池输出电流大时,也会把干电池的电压从1.5V拉低到1V左右. 更多的是客户对于1V时要能升到3V或者3 ...
- 一个简单的IM聊天程序Pie IM(以后会更新)
这个程序用多线程,实现设备之间的聊天,支持win10通知,欢迎下载 依赖的第三方库 win10toast 代码 将以下代码写入任意.py文件 1 print('Welcome to use Pie I ...