1. 配置全局异常和自定义异常
- 异常处理类(包括全局和自定义)
@RestControllerAdvice
public class CustomExtHandler {
/**
* 处理全局异常
* 返回json数据,由前端去判断加载什么页面(推荐)
*/
@ExceptionHandler(value = Exception.class)
Object handleException(Exception e, HttpServletRequest request) {
log.error("url [{}], msg [{}]", request.getRequestURL(), e.getMessage());
Map<String, Object> map = new HashMap<>(3);
map.put("code", 500);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
/**
* 处理自定义异常
* 返回json数据,由前端去判断加载什么页面(推荐)
*/
@ExceptionHandler(value = MyException.class)
Object handleMyException(MyException e, HttpServletRequest request) {
log.error("url [{}], msg [{}]", request.getRequestURL(), e.getMessage());
Map<String, Object> map = new HashMap<>(3);
map.put("code", e.getCode());
map.put("msg", e.getMsg());
map.put("url", request.getRequestURL());
return map;
}
}
- 自定义异常类
@Getter
@Setter
public class MyException extends RuntimeException {
//状态码
private String code;
//错误信息
private String msg;
public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
}
}
2.返回自定义页面
- 创建自定义页面位置,位置如下图:
<!DOCTYPOE html>
<html>
<head>
<meta charset="UTF-8">
<title>Error Page</title>
</head>
<body>页面加载异常</body>
</html>

error.html位置
- 引入thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 异常处理类
@RestControllerAdvice
public class CustomExtHandler {
/**
* 处理自定义异常
* 进行页面跳转
*/
@ExceptionHandler(value = MyException.class)
Object handleMyException(MyException e, HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("error.html");
modelAndView.addObject("msg", e.getMessage());
return modelAndView;
}
}
网友评论