美文网首页
SpringBoot2.x中WebFlux/SpringMVC全

SpringBoot2.x中WebFlux/SpringMVC全

作者: r09er | 来源:发表于2018-08-28 22:32 被阅读674次

默认的全局异常类:DefaultErrorWebExceptionHandler

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

SpringBoot1.x中使用的是DefaultErrorViewResolver

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

  • 1.try-catch 使用自定义返回类
  • 2.通过全局异常将错误统一包装处理

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

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

  • 1.类上添加@RestControllerAdvice注解
  • 2.方法上添加@ExceptionHandler标明处理的异常类型,

可以添加自定义的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("内部错误");
    }
}

相关文章

网友评论

      本文标题:SpringBoot2.x中WebFlux/SpringMVC全

      本文链接:https://www.haomeiwen.com/subject/ahrcwftx.html