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);
}
}
正常取到請求路徑以及異常信息: