1 异常分类
-
ERROR : 错误 jvm虚拟机生成,如 系统崩溃,虚拟机错误,内存空间不足,方法调用栈溢等(程序处理不了)。
-
Exception :
(1)运行时异常: 一般是由程序逻辑错误引起的,出现运行时异常后,如果没有捕获处理这个异常(即没有catch),系统会把异常一直往上层抛,一直到最上层,那么出现运行时异常之后,要么是线程中止,要么是主程序终止。
(2)非运行时异常:必须进行处理的异常,如果不处理,程序就不能编译通过。如IOException、SQLException等.
2 异常处理
1 默认异常页面
(1)如果是浏览器访问,则SpringBoot默认返回错误页面;
- 请求头如下:
(2)如果是其他客户端访问 比如app,则默认返回JSON数据。
{
"timestamp": 1529479254647,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/aaa1"
}
- 请求头如下
2 自定义异常页面
(1)动态的异常页面,可以采用的页面模板有 jsp、freemarker、thymeleaf。动态异常页面,也支持 404.html 或者 4xx.html ,但是一般来说,由于动态异常页面可以直接展示异常详细信息,所以就没有必要挨个枚举错误了 ,直接定义 4xx.html(这里使用thymeleaf模板)或者 5xx.html 即可。注意,动态页面模板,不需要开发者自己去定义控制器,直接定义异常页面即可 ,Spring Boot 中自带的异常处理器会自动查找到异常页面
(2)自定义静态异常页面,命名同上
即Springboot中默认的静态资源路径有4个,分别是:
classpath:/METAINF/resources/,
classpath:/resources/,
classpath:/static/,
classpath:/public/
优先级顺序为:META-INF/resources > resources > static > public
错误代码的类型很多,如400、403、404等等,如果按照上面的方法,需要添加很多页面而
SpringBoot提供了通用的命名方式,就是使用4xx.html、5xx.html命名,如:
4xx.html表示能匹配到400、403、404……等错误
5xx.html表示能匹配到500、501、502……等错误
如果404.html和4xx.html同时存在时,优先使用最匹配的,即当发生404错误时,优先匹配404.html页面
3 自定义异常处理类
Spring的异常处理有3种形式,可以总结如下:
将异常对象映射为HTTP状态码(@ResponseStatus)
本地处理(@ExceptionHandler)
全局处理(@ControllerAdvice结合@ExceptionHandler)
(1)自定义 异常类 继承 运行时异常
public class UserNotExistException extends RuntimeException {
private static final long serialVersionUID = -6112780192479692859L;
private String id;
public UserNotExistException(String id) {
super("user not exist"); // 调用父类构造方法 设置message
this.id = id; // 如果 在方法中直接抛出 这个异常 id是不会显示的
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
(2)编写一个控制器,用于抛出异常
* 此种方法返回的信息 只有message,没有id
@Controller
public class MyController {
@ResponseBody
@RequestMapping("/exception")
public String ee(String param){
if(param.equals("aa")){
throw new UserNotExistException ("抛出自定义异常");
}
return "没有抛出异常";
}
}
(3)定义全局异常处理类,所有Controller抛出的异常都会被 处理
* 此种方法可以返回自定义信息比如 id
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(UserNotExistException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // http 状态码
public Map<String, Object> handleUserNotExistException(UserNotExistException ex) {
Map<String, Object> result = new HashMap<>();
result.put("id", ex.getId());
result.put("message", ex.getMessage());
return result;
}
}






浙公网安备 33010602011771号