gpt4 book ai didi

java - 自定义 Zuul 异常

转载 作者:太空狗 更新时间:2023-10-29 22:42:56 27 4
gpt4 key购买 nike

我在 Zuul 中有一个场景,其中路由 URL 的服务也可能已关闭。因此响应主体在 JSON 主体响应中抛出 500 HTTP 状态和 ZuulException。

{
"timestamp": 1459973637928,
"status": 500,
"error": "Internal Server Error",
"exception": "com.netflix.zuul.exception.ZuulException",
"message": "Forwarding error"
}

我想做的就是自定义或删除 JSON 响应,并可能更改 HTTP 状态代码。

我尝试使用@ControllerAdvice 创建一个异常处理程序,但处理程序未捕获该异常。

更新:

所以我扩展了 Zuul Filter 我可以看到它在执行错误后进入运行方法然后我该如何更改响应。以下是我到目前为止得到的。我在某处读到有关 SendErrorFilter 的内容,但我该如何实现它以及它有什么作用?

public class CustomFilter extends ZuulFilter {

@Override
public String filterType() {
return "post";
}

@Override
public int filterOrder() {

return 1;
}

@Override
public boolean shouldFilter() {
return true;
}

@Override
public Object run() {
final RequestContext ctx = RequestContext.getCurrentContext();
final HttpServletResponse response = ctx.getResponse();
if (HttpStatus.INTERNAL_SERVER_ERROR.value() == ctx.getResponse().getStatus()) {
try {
response.sendError(404, "Error Error"); //trying to change the response will need to throw a JSON body.
} catch (final IOException e) {
e.printStackTrace();
} ;
}

return null;
}

将其添加到具有@EnableZuulProxy 的类中

@Bean
public CustomFilter customFilter() {
return new CustomFilter();
}

最佳答案

我们终于成功了 [由我的一位同事编写]:-

public class CustomErrorFilter extends ZuulFilter {

private static final Logger LOG = LoggerFactory.getLogger(CustomErrorFilter.class);
@Override
public String filterType() {
return "post";
}

@Override
public int filterOrder() {
return -1; // Needs to run before SendErrorFilter which has filterOrder == 0
}

@Override
public boolean shouldFilter() {
// only forward to errorPath if it hasn't been forwarded to already
return RequestContext.getCurrentContext().containsKey("error.status_code");
}

@Override
public Object run() {
try {
RequestContext ctx = RequestContext.getCurrentContext();
Object e = ctx.get("error.exception");

if (e != null && e instanceof ZuulException) {
ZuulException zuulException = (ZuulException)e;
LOG.error("Zuul failure detected: " + zuulException.getMessage(), zuulException);

// Remove error code to prevent further error handling in follow up filters
ctx.remove("error.status_code");

// Populate context with new response values
ctx.setResponseBody(“Overriding Zuul Exception Body”);
ctx.getResponse().setContentType("application/json");
ctx.setResponseStatusCode(500); //Can set any error code as excepted
}
}
catch (Exception ex) {
LOG.error("Exception filtering in custom error filter", ex);
ReflectionUtils.rethrowRuntimeException(ex);
}
return null;
}
}

关于java - 自定义 Zuul 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461493/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com