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

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

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

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

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

@Override
    protected Mono renderErrorResponse(ServerRequest request) {
        Map 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("运行楚楚了");
}

然后测试即可
微服务版本全局异常拦截返回自定义信息_第1张图片

你可能感兴趣的:(框架搭建,java,开发语言)