我们在开发测试的时候难免会碰到各种各样的异常,如果在浏览器中碰到异常,类似404或者我们自己定义的异常,SpringBoot会使用它给我们默认提供的异常页面,这个用户体验不怎么友好,接下来我们就自己定制一个类似SpringMvc中的异常处理器,来解决这一问题。
其实除了我们这个异常处理器,我们还有更简单的做法,但这个需要了解到SpringBoot的错误处理机制,这个我下一篇博客再去记录它。
首先我们需要编写一个ExceptionHandler
和自己定义的一个异常(略)
@ControllerAdvice //使用ControllerAdvice注解标注
public class MyExceptionHandler {
@ExceptionHandler //标注为异常处理器
public String demo(MyException exception){ //可直接在参数获取异常
HashMap<String, Object> map = new HashMap<>();
map.put("exception",exception.getMessage()); //存入到request中,方便等等验证
return "/exceptionPage";
}
}
接着我们简单的编写一个html页面和跳转的映射来验证这个异常处理器是否起了作用
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>异常</title>
</head>
<body>
<h1>异常:[[exception]]</h1>
</body>
</html>
因为使用thymeleaf需要结果服务器,我们可以使用一个controller来配置映射:
@GetMapping(path = "/exceptionPage")
public String exception(){
return "forward:/exceptionPage.html";
}
service:
public class UserService {
public void demoException() throws MyException {
throw new MyException("我来也");
}
}
随便在别的方法中调用new MyException().demoException
看看能不能跳转到指定页面.
bingo!改天会记录下SpringBoot
的错误管理机制.