微服务版本全局异常拦截返回自定义信息

创建全局配置拦截类:extends DefaultErrorWebExceptionHandler

​ 创建构造函数(此处省略)

指定相应处理方法
@Override
protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
}

renderErrorResponse 此方法Override 需要重写自定义自己的方法

@Override
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        Map<String, Object> error = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        int errorStatus = getHttpStatus(error);
        Throwable throwable = getError(request);
        return ServerResponse.status(errorStatus)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(new ExceptionHandlerAdvice().handle(throwable)));
    }

基本都是不需要改动什么

new ExceptionHandlerAdvice():

​ 自定义处理返回类 handle()


```java
@ExceptionHandler(value = {Exception.class})  //自定义需要处理的异常类型
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handle(Exception ex) {
    log.error("exception:{}", ex.getMessage());
    return Result.error(null,BaseConstant.SC_INTERNAL_SERVER_ERROR,ex.getMessage());
}

@ExceptionHandler(value = {Throwable.class})   //直接抛出对应的异常处理
public Result handle(Throwable throwable) {
    Result result = null;
    if (throwable instanceof ConnectTimeoutException) {
        result = handle((ConnectTimeoutException) throwable);
    } else if (throwable instanceof ConnectTimeoutException) {
        result = handle((ConnectTimeoutException) throwable);
    } else if (throwable instanceof NotFoundException) {
        result = handle((NotFoundException) throwable);
    } else if (throwable instanceof RuntimeException) {
        result = handle((RuntimeException) throwable);
    } else if (throwable instanceof Exception) {
        result = handle((Exception) throwable);
    }else if (throwable instanceof IndexOutOfBoundsException) {
        result = handle((IndexOutOfBoundsException) throwable);
    }
    return result;
}
@ControllerAdvice   //注入springBean全局拦截
public class BaseExceptionHandler {
    /**
     * BaseException 异常捕获处理
     * @param ex 自定义BaseException异常类型
     * @return Result
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result<?> handleException(RuntimeException ex) {
        log.error("程序异常:" + ex);
        return Result.error(null,BaseConstant.ERROR,ex.getMessage());
    }
}

添加测试方法

@GetMapping("/init")
public String get(){
    throw  new RuntimeException("运行楚楚了");
}

然后测试即可
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

平常心丷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值