/**
* 返回自定义的错误页面
* @author Paracosm
* @ControllerAdvice 拦截所有的标注有controller这个注解的控制器,
* @ExceptionHandler 标识这个方法可以做异常处理的 Exception.class表示只要是exception级别的都可以
*/
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {
/*private Logger logger = LoggerFactory.getLogger(this.getClass());*/
@ExceptionHandler(Exception.class)
public ModelAndView exceptionHandler(HttpServletRequest request,Exception e) throws Exception {
/*记录*/
log.error("Request URL : {}, Exception : {}", request.getRequestURI(),e.getMessage());
/*通过注解工具找一个注解有没有存在,如果指定了状态就不应该拦截它 */
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
throw e;
}
/*记录之后希望返回的错误页面*/
ModelAndView mv = new ModelAndView();
mv.addObject("url",request.getRequestURI());
/*获取异常信息*/
mv.addObject("exception",e);
mv.setViewName("error/error");
return mv;
}
}
自定义异常类
/**
* @Author Paracosm
* @Date 2020/12/30 20:29
* @Version 1.0
*/
/*要继承runtimeexception才能捕获
* 如果要跳转到404页面还需要指定一个返回的状态码 @ResponseStatus(HttpStatus.NOT_FOUND)
* */
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
public NotFoundException() {
}
public NotFoundException(String message) {
super(message);
}
public NotFoundException(String message, Throwable cause) {
super(message, cause);
}
}
测试
@GetMapping("/")
public String index(){
/*int i = 9/0;*/ // error
String blog = null;
if (blog == null) {
throw new NotFoundException("博客不存在"); //404
}
return "index";
}