统一异常处理Exception

1.注解:@ControllerAdvice

   1.1.@ControllerAdvice是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适           用于    所有使用@RequestMapping方法。

   1.2. @ControllerAdvice常用来与@ExceptionHandler配合,其它两个不常用。

2.定义统一异常处理工具类

@ResponseBody
@ControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    public ResultMap hadndle(Exception e){
        e.printStackTrace();
        return Result.error("Server Error");
    }

    @ExceptionHandler(value = MyException.class)
    public ResultMap hadndle(MyException e){
        e.printStackTrace();
        return Result.error(e.getMessage());
    }
}

3.业务代码

抛出自定义异常,普通一场则会抛出"Server Error"

throw new MyException("出错了");

猜你喜欢

转载自blog.csdn.net/xyy1028/article/details/80207721