SpringCloudGateway笔记(11)-异常拦截

使用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
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值