SpringBoot2.x中WebFlux/SpringMVC全

2018-08-28  本文已影响674人  r09er

默认的全局异常类:DefaultErrorWebExceptionHandler

在SpringBoot中,默认的全局异常处理类是DefaultErrorWebExceptionHandler,会根据请求头中的Accept参数返回视图或者数据(JSON).

SpringBoot1.x中使用的是DefaultErrorViewResolver

从WebFlux的DefaultErrorWebExceptionHandler和WebMvc中的实现有区别,但是最终的效果是一致的
但是在日常开发中,通常需要自定义错误的返回格式.一般有2种操作方法

第一种方法就不再赘述了,直接上第二种解决

1.定义全局异常处理类,

可以添加自定义的Exception实现,
也可以通过处理的异常类对异常捕获的粒度进行控制

@RestControllerAdvice
public class CustomExceptionHandler {
    @ExceptionHandler(CustomException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public DefaultResult handleCustomException(CustomException e) {
        logger.error(e.getMessage());
        return DefaultResult.fail(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public DefaultResult handleException(Exception e) {
        logger.error(e.getMessage());
        return DefaultResult.fail("内部错误");
    }
}
上一篇 下一篇

猜你喜欢

热点阅读