Spring Cloud Gateway Hystrix fallback获取异常信息的处理

Gateway Hystrix fallback获取异常信息

gateway fallback后,需要知道请求的是哪个接口以及具体的异常信息,根据不同的请求以及异常进行不同的处理。一开始根据网上一篇博客上的做法:

pom.xml:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

application.yml:

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: false
          lowerCaseServiceId: true
      routes:
        - id: auth-server
          uri: lb://MS-OAUTH2-SERVER
          predicates:
            - Path=/**
      default-filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/fallback

然后fallback就是这样:

@RestController
@Slf4j
public class FallbackController {

    @RequestMapping(value = "/fallback")
    @ResponseStatus
    public Mono<Map<String, Object>> fallback(ServerWebExchange exchange, Throwable throwable) {
        Map<String, Object> result = new HashMap<>(3);
        ServerHttpRequest request = exchange.getRequest();
        log.error("接口调用失败,URL={}", request.getPath().pathWithinApplication().value(), throwable);
        result.put("code", 60002);
        result.put("data", null);
        result.put("msg", "接口调用失败!");
        return Mono.just(result);
    }
}

但是测试发现,这样取出来的接口地址只是“/fallback”本身,并且没有异常信息:

后来我重新到HystrixGatewayFilterFactory类中去查看,发现了异常信息其实在exchange里:

而请求的接口也通过debug找到了:

所以将代码改成如下:

@RestController
@Slf4j
public class FallbackController {

    @RequestMapping(value = "/fallback")
    @ResponseStatus
    public Mono<Map<String, Object>> fallback(ServerWebExchange exchange) {
        Map<String, Object> result = new HashMap<>(3);
        result.put("code", 60002);
        result.put("data", null);
        Exception exception = exchange.getAttribute(ServerWebExchangeUtils.HYSTRIX_EXECUTION_EXCEPTION_ATTR);
        ServerWebExchange delegate = ((ServerWebExchangeDecorator) exchange).getDelegate();
        log.error("接口调用失败,URL={}", delegate.getRequest().getURI(), exception);
        if (exception instanceof HystrixTimeoutException) {
            result.put("msg", "接口调用超时");
        } else if (exception != null && exception.getMessage() != null) {
            result.put("msg", "接口调用失败: " + exception.getMessage());
        } else {
            result.put("msg", "接口调用失败");
        }
        return Mono.just(result);
    }
}

正常取到请求路径以及异常信息:

关于 hystrix 的异常 fallback method wasn't found

消费者服务--service 的实现如下:

@Service
public class BookService {
    @Autowired
    public RestTemplate  restTemplate;
    @HystrixCommand(fallbackMethod = "addServiceFallback")
    public  Book   getBook( Integer  bookId ){
        return  restTemplate.getForObject("http://provider-service/boot/book?bookId={bookId}",Book.class , bookId);
    }
    public  String  addServiceFallback(){
        System.out.println("error addServiceFallback.... ");
        return  "error" ;
    }
}

就会出现如下所述的异常

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri May 25 14:27:51 CST 2018
There was an unexpected error (type=Internal Server Error, status=500).
fallback method wasn't found: addServiceFallback([class java.lang.Integer])

这是因为指定的 备用方法 addServiceFallback 和 原方法getBook 的参数个数,参数类型 不同造成的;

修改addServiceFallback 方法:

public  String addServiceFallback(Integer  bookId){
    System.out.println("error addServiceFallback.... ");
    return  "error" ;
}

继续运行,就会出现如下所述的异常

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Fri May 25 14:32:24 CST 2018
There was an unexpected error (type=Internal Server Error, status=500).
Incompatible return types. Command method: public com.bmcc.springboot.model.Book com.bmcc.springboot.service.BookService.getBook(java.lang.Integer); Fallback method: public java.lang.String com.bmcc.springboot.service.BookService.addServiceFallback(java.lang.Integer); Hint: Fallback method 'public java.lang.String com.bmcc.springboot.service.BookService.addServiceFallback(java.lang.Integer)' must return: class com.bmcc.springboot.model.Book or its subclass

这是因为指定的 备用方法 addServiceFallback 和 原方法getBook 虽然 参数个数,参数类型 相同 ,但是 方法的返回值类型不同造成的;

修改addServiceFallback 方法:

public  Book  addServiceFallback(Integer  bookId){
    System.out.println("error addServiceFallback.... ");
    return  new Book() ;
}

继续运行,这样就可以看到当一个服务提供者异常关闭时, 消费者(消费者采用轮询的方式消费服务)再继续访问服务时,不会抛出异常页面,而是如下:

{"bookId":0,"bookName":null,"price":null,"publisher":null}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解SpringCloud Finchley Gateway 统一异常处理

    SpringCloud Finchley Gateway 统一异常处理 全文搜索[@@]搜索重点内容标记 1 . 问题:使用SpringCloud Gateway时,会出现各种系统级异常,默认返回HTML. 2 . Finchley版本的Gateway,使用WebFlux形式作为底层框架,而不是Servlet容器,所以常规的异常处理无法使用 翻阅源码,默认是使用DefaultErrorWebExceptionHandler这个类实现结构如下: 可以实现参考DefaultErrorWebExcep

  • Spring Cloud Gateway全局通用异常处理的实现

    为什么需要全局异常处理 在传统 Spring Boot 应用中, 我们 @ControllerAdvice 来处理全局的异常,进行统一包装返回 // 摘至 spring cloud alibaba console 模块处理 @ControllerAdvice public class ConsoleExceptionHandler { @ExceptionHandler(AccessException.class) private ResponseEntity<String> handleAc

  • Spring Cloud Hystrix异常处理方法详解

    这篇文章主要介绍了Spring Cloud Hystrix异常处理方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 在调用服务执行HsytrixCommand实现的run()方法抛出异常时,除HystrixBadRequestException之外,其他异常都会认为是Hystrix命令执行失败并触发服务降级处理逻辑. 异常处理 当Hystrix命令因为异常(除了HystrixBadRequestException异常)进入服务降级逻辑之后

  • Spring Cloud Gateway全局异常处理的方法详解

    前言 Spring Cloud Gateway是Spring官方基于Spring 5.0,Spring Boot 2.0和Project Reactor等技术开发的网关,Spring Cloud Gateway旨在为微服务架构提供一种简单而有效的统一的API路由管理方式.Spring Cloud Gateway作为Spring Cloud生态系中的网关,目标是替代Netflix ZUUL,其不仅提供统一的路由方式,并且基于Filter链的方式提供了网关基本的功能,例如:安全,监控/埋点,和限流等

  • Spring Cloud Gateway Hystrix fallback获取异常信息的处理

    Gateway Hystrix fallback获取异常信息 gateway fallback后,需要知道请求的是哪个接口以及具体的异常信息,根据不同的请求以及异常进行不同的处理.一开始根据网上一篇博客上的做法: pom.xml: <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId&g

  • Spring Cloud Gateway 如何修改HTTP响应信息

    Gateway 修改HTTP响应信息 实践Spring Cloud的过程中,使用Gateway作为路由组件,并且基于Gateway实现权限的验证.拦截.过滤,对于下游微服务的响应结果,我们总会有需要修改以统一数据格式,或者修改过滤用户没有权限看到的数据信息,这时候就需要有一个能够修改响应体的Filter. Spring Cloud Gateway 版本为2.1.0 在当前版本,ModifyRequestBodyGatewayFilterFactory是官方提供的修改响应体的参考类,This fi

  • 解决Spring Cloud Gateway获取body内容,不影响GET请求的操作

    废话 这几天换了新工作,需要重新开发一套系统,技术选用Spring Cloud.在对接终端接口的时候要做验签,就涉及到在网关做拦截器,然后取出BODY里面的数据. 网上找了几个方法,有的拿不到数据,有的拿到数据之后不支持GET请求了.没有一个合理的解决办法,最后想到在动态路由构建的时候可以指定METHOD,于是有了如下解决办法 解决 @Bean public RouteLocator vmRouteLocator(RouteLocatorBuilder builder) { return bui

  • Spring Cloud Gateway 获取请求体(Request Body)的多种方法

    一.直接在全局拦截器中获取,伪代码如下 private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest){ Flux<DataBuffer> body = serverHttpRequest.getBody(); AtomicReference<String> bodyRef = new AtomicReference<>(); body.subscribe(buffer -> {

  • 详解Spring Cloud Gateway 数据库存储路由信息的扩展方案

    动态路由背景 ​ 无论你在使用Zuul还是Spring Cloud Gateway 的时候,官方文档提供的方案总是基于配置文件配置的方式 例如: # zuul 的配置形式 routes: pig-auth: path: /auth/** serviceId: pig-auth stripPrefix: true # gateway 的配置形式 routes: - id: pigx-auth uri: lb://pigx-auth predicates: - Path=/auth/** filte

  • 解决spring cloud gateway 获取body内容并修改的问题

    之前写过一篇文章,如何获取body的内容. Spring Cloud Gateway获取body内容,不影响GET请求 确实能够获取所有body的内容了,不过今天终端同学调试接口的时候和我说,遇到了400的问题,报错是这样的HTTP method names must be tokens,搜了一下,都是说https引起的.可我的项目还没用https,排除了. 想到是不是因为修改了body内容导致的问题,试着不修改body的内容,直接传给微服务,果然没有报错了. 问题找到,那就好办了,肯定是我新构

  • spring cloud gateway集成hystrix全局断路器操作

    gateway集成hystrix全局断路器 pom.xml添加依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> 在配置文件中,增加spring.cloud.gateway.default-filters: defa

  • spring cloud gateway集成hystrix实战篇

    spring cloud gateway集成hystrix 本文主要研究一下spring cloud gateway如何集成hystrix maven <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> 添加spring-

  • 聊聊Spring Cloud Gateway过滤器精确控制异常返回问题

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 本篇概览在<Spring Cloud Gateway修改请求和响应body的内容>一文中,咱们通过filter成功修改请求body的内容,当时留下个问题:在filter中如果发生异常(例如请求参数不合法),抛出异常信息的时候,调用方收到的返回码和body都是Spring Cloud Gateway框架处理后的,调用方无法根据这些内容知道真正的错误原因

随机推荐