在跟着视频做springboot与thymeleaf自定义异常以及定制异常界面的时候exception和message的值获取不到,但是时间戳timestamp和错误码status可以获取到
自定义的异常
public class UserNotExistException extends RuntimeException{
public UserNotExistException() {
super("用户不存在");
}
}
当登录名为aaa时,抛出自定义异常:用户不存在
@RequestMapping("hello")
@ResponseBody
public String hello(@RequestParam("user") String user){
if (user.equals("aaa")){
throw new UserNotExistException();
}
return "HelloWorld";
}
前端取值页面:
<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>
<h2>exception:[[${exception}]]</h2>
<h2>message:[[${message}]]</h2>
测试效果:
exception和message都为空,但是异常对象和错误信息都在控制台打印出来了,只是没有在页面显示而已
原因是没有在配置文件里指定,server错误信息要包含异常对象和异常信息:
解决方法,在properties文件里面加上这两句:
#自定义异常处理页面,异常对象。异常信息
server.error.include-exception=true
server.error.include-message=always
就可以显示
视频里面用的是springboot1.x的版本,但我用的是2.x的,特性方面会有很多变化,以后再遇到类似的坑都会记录下来