java - 自定义 Zuul 异常

标签 java spring-boot spring-cloud microservices netflix-zuul

我在 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/

相关文章:

c# - 导出可运行的应用程序

Spring:ApplicationStartingEvent 不能转换为 ApplicationPreparedEvent for OptaPlanner Examination App

springfox 不能与 spring-boot-admin-server 一起使用

java - Maven 将 jar 添加到 war 中,但依赖项中不存在 :tree

spring - 如何在 POST 中发送 ClientId 和 ClientSecret,而不是在带有 ClientCredentialsAccessTokenProvider 的 header 中

java - 在 Spring redis session 中保存对象时出现 ClassCastException

java - maven不将lib打包到jar中

java - 如何使线性布局出现在 GridView 中?

java - 如何缩短类似按钮的 findViewById 和 setOnClickListener ?

docker - 无法在Docker中链接Consul和Spring Boot应用