【问题标题】:How to customize Spring boot controller API response for ZuulException如何为 ZuulException 自定义 Spring Boot 控制器 API 响应
【发布时间】:2019-04-15 05:24:16
【问题描述】:

我们正在为 REST API 使用 Zuul、Eureka 和 Spring Boot 应用程序服务。

假设我的 spring boot 服务已关闭,当我尝试使用 Zuul API 网关访问 API 时,我收到 ZuulException 并且响应如下:

{
    "timestamp": "2018-10-12T14:29:09.632+0000",
    "status": 500,
    "error": "Internal Server Error",
    "exception": "com.netflix.zuul.exception.ZuulException",
    "message": "GENERAL"
}

我想自定义响应格式如下:

{
    "success": false,
    "message": "Service is down. Please try later"
}

我尝试实现https://stackoverflow.com/a/39841785/5506061,但它对我不起作用。

请建议如何自定义 ZuulException 的响应。

【问题讨论】:

    标签: spring-boot netflix-zuul


    【解决方案1】:

    如果需要,您可以实现自己的 FallbackProvider 并根据原因自定义响应。

    类似:

    @Component
    public class CustomFallbackBasedOnCause implements FallbackProvider {
    
    private static final String DEFAULT_MSG = "{\"success\": false,\"message\": \"Service is down. Please try later\"}";
    
    @Override
    public String getRoute() {
        return "*"; // * = all routes
    }
    
    @Override
    public ClientHttpResponse fallbackResponse(final Throwable cause) {
        if (cause instanceof HystrixTimeoutException) {
            return response(HttpStatus.GATEWAY_TIMEOUT);
        } else {
            return fallbackResponse();
        }
    }
    
    @Override
    public ClientHttpResponse fallbackResponse() {
        return response(HttpStatus.INTERNAL_SERVER_ERROR);
    }
    
    private ClientHttpResponse response(final HttpStatus status) {
        return new ClientHttpResponse() {
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return status;
            }
    
            @Override
            public int getRawStatusCode() throws IOException {
                return status.value();
            }
    
            @Override
            public String getStatusText() throws IOException {
                return status.getReasonPhrase();
            }
    
            @Override
            public void close() {
            }
    
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream(DEFAULT_MSG.getBytes());
            }
    
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                return headers;
            }
        };
    }
    }
    

    正如您在 getRoute() 方法中所见,您可以指定此 customFallback 是用于所有路由 (return "*") 还是用于特定路由。

    如果您使用 Registry 服务(例如 Eureka)。您不指定路由 URL,而是指定服务 ID。 return "SERVICEID"

    【讨论】:

      猜你喜欢
      • 2016-08-30
      • 2020-03-17
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      相关资源
      最近更新 更多