在项目中如果我们想统一进行全局的异常处理,那么我们可以使用
@ControllerAdvice 和 @ExceptionHandler(拦截的异常类) 两个注解来进行全局的异常处理。
java
@ControllerAdvice
public class RuntimeExceptionHandler {
/**
* 全局统一异常处理
* @param exception
* @return
*/
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public R handler(RuntimeException exception) {
return R.error(exception.getMessage());
}
@ExceptionHandler(CartExceptionHandler.class)
public R userHandler(CartExceptionHandler exception) {
return R.error("购物车无此商品");
}
}
这里我们可以自定义自己的异常处理类:
java
public class CartExceptionHandler extends RuntimeException {
}
@ControllerAdvice : 用于定义一个类作为全局异常处理器。使用这个类可以捕获和处理来自Spring MVC控制器的异常。
@ExceptionHandler(拦截的异常类) : 这里处理的异常类可以是多个,以数组的形式传递值就可以。