核心注解 @RestControllerAdvice
加了这个注解,会把所有带有@RequestMapping
的controller当做一个切面。
暂时写这么多,有能补充的我再加上。
最后补上代码
package com.li.ta.aspect;
import com.li.ta.common.exception.CommonException;
import com.li.ta.common.utils.R;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* desc 捕获全局异常
*
* @author zh 2021/01/08 10:02 上午
*/
@RestControllerAdvice(basePackages = "com.li.ta.controller")
public class ExceptionAspect {
@ResponseBody
@ExceptionHandler(value= Exception.class)
public R handleValidException(Exception e) {
// value 就是要处理异常的类型
Throwable cause = e.getCause();
return R.error(100000, "出现了了意料之外的错误。");
}
@ResponseBody
@ExceptionHandler(value= BadSqlGrammarException.class)
public R handleValidException(BadSqlGrammarException e) {
return R.error(100001, "数据操作错误");
}
@ResponseBody
@ExceptionHandler(value= NullPointerException.class)
public R handleValidException(NullPointerException e) {
return R.error(100002, "空指针异常!");
}
@ResponseBody
@ExceptionHandler(value= CommonException.class)
public R handleValidException(CommonException e) {
return R.error(100003, "请登录!");
}
}