使用SpringCloudGateway的全局异常拦截
其实这个应该是webflux的全局异常拦截,由于gateway使用的是webflux的底层,不是servlet容器,异常处理需要继承ErrorWebExceptionHandler
具体实现如下
@Slf4j
@Component
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
@Override
public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
log.info("GLOBAL EXCEPTION:{}, \n{}", serverWebExchange.getRequest().getPath(), throwable);
JSONObject object = new JSONObject();
if (throwable instanceof NotFoundException) {
object.put("message", "not found");
} else if (throwable instanceof ResponseStatusException) {
object.put("message", "status exception");
} else {
object.put("message", "exception");
}
DataBufferFactory bufferFactory = serverWebExchange.getResponse().bufferFactory();
serverWebExchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
return serverWebExchange.getResponse().writeWith(Flux.just(bufferFactory.wrap(object.toJSONString().getBytes())));
}
}
测试一下
在gateway的demo里面写一个controller
@Slf4j
@RestController
@RequestMapping("/demo")
public class DemoController {
@GetMapping("/exception")
public String test(){
int a = 1/0;
return "success";
}
}
发送请求
查看后台打印
2019-06-29 23:05:53.659 INFO 3948 --- [ctor-http-nio-1] c.m.d.g.c.GlobalExceptionHandler : GLOBAL EXCEPTION:/demo/exception,
{}
java.lang.ArithmeticException: / by zero
at com.mt.demo.gateway.controller.DemoController.test(DemoController.java:21) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
at org.springframework.web.reactive.result.method.InvocableHandlerMethod.lambda$invoke$0(InvocableHandlerMethod.java:137) ~[spring-webflux-5.1.7.RELEASE.jar:5.1.7.RELEASE]
at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:141) ~[reactor-core-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at reactor.core.publisher.MonoFlatMap.subscribe(MonoFlatMap.java:53) ~[reactor-core-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at reactor.core.publisher.MonoDefer.su