为了统一处理异常,可以有个全局异常处理的类。用@RestControllerAdvice修饰。
@RestControllerAdvice:只能修饰类。
注解将作用在所有注解了@RequestMapping的控制层(控制器)的方法上。
该注解包含了@ControllerAdvice和@ResponseBody。而@ControllerAdvice又只包含了@Component。
@ExceptionHandler:只能修饰方法。
用于指定捕获异常后的处理方法。
@ExceptionHandler的参数为需要被捕获处理的异常类(需要该类继承Throwable)。如果为空,则默认为@ExceptionHandler修饰的方法的参数列表中列出的任何异常。
@ExceptionHandler通常与@RestControllerAdvice配合使用时,用于全局处理控制层(控制器)中出现的异常。
/** * 全局异常处理器。 * RestControllerAdvice和ControllerAdvice是全局接口异常处理的类。 * 当发生异常没有捕获时,便会触发这个异常。 * * @author zhengqingquan */ @RestControllerAdvice @Slf4j public class GlobalExceptionHandler { /** * BusinessException为自定义的业务异常。 * 这个方法只去捕获BusinessException异常。 * * @return */ @ExceptionHandler(BusinessException.class) public void BusinessExceptionHandler(BusinessException e) { log.error("businessException" + e.getMessage(), e); } /** * 运行时异常 * * @param e * @return */ @ExceptionHandler(RuntimeException.class) public void RuntimeExceptionHandler(RuntimeException e) { log.error("runtimeException", e); } }