前言
SpringBoot对异常有自己的一套处理机制,在实际开发中这个也非常有用,可以增强代码的健壮性,也是一个非常基础的技能,下面就简单说下在SpringBoot工程中怎么使用异常处理!
实现方式
1. 自定义异常页面
我们可以通过在src/main/resources/resources/error
路径下定义友好的异常页面,比如定义一个500.html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>500</title>
</head>
<body>
系统内部异常
</body>
</html>
我们一般常见的错误有404和500,这是最常见的,在上面定义的目录下面定义404.html或者500.html,当发生对应的错误就会跳到这两个页面,这是最简单的!
2.自定义异常处理
前后端分离的时候,我们想定义一些异常提示,SpringBoot也有方法@ControllerAdvice
和@RestControllerAdvice
我们手动定义一个UserNotExistException,继承RuntimeException。
public class UserNotExistException extends RuntimeException{
private static final long serialVersionUID = -1574716826948451793L;
private String id;
public UserNotExistException(String id){
super("user not exist");
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
然后定义一个Controller异常处理类ControllerExceptionHandler:
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(UserNotExistException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> handleUserNotExistsException(UserNotExistException e) {
Map<String, Object> map = new HashMap<>();
map.put("id", e.getId());
map.put("message", e.getMessage());
return map;
}
}
编写完自定义异常处理逻辑后,我们将UserController中的方法抛出的异常改为UserNotExistException:
@GetMapping("/{id:\\d+}")
public void get(@PathVariable String id) {
throw new UserNotExistException(id);
}
访问:http://localhost:8080/user/1
是不是很简单?你学会(fei)了吗?