SpringBoot中在有模板引擎的情况下,自定义错误响应页面,但是exception和message的值获取不到,时间戳timestamp和错误码status却可以获取到,
1)自定义的异常
public class UserNotExistException extends RuntimeException{
public UserNotExistException(){
super("用户不存在");
}
}
- 1
- 2
- 3
- 4
- 5
2)当用户名为come的时候,用户会不存在
@ResponseBody
@RequestMapping("/hello")
public String hello(@RequestParam("user") String user){
if (user.equals("come")){
//抛出一个自定义异常 p45
throw new UserNotExistException();
}
return "Hello";
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
3)前端页面获取到的信息:
<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>
<h2>exception:[[${exception}]]</h2>
<h2>message:[[${message}]]</h2>
- 1
- 2
- 3
- 4
4)访问后的结果
exception和message都为空,但是异常对象和错误信息都在控制台打印出来了,只是没有在页面显示而已
如图:
主要原因是没有在配置文件里指定,server错误信息要包含异常对象和异常信息(SpringBoot2.0以上的版面需要在配置文件指定):
解决方法,在properties文件里面加上这两句:
#自定义异常处理页面,异常对象。异常信息
server.error.include-exception=true
server.error.include-message=always
- 1
- 2
- 3
在配置文件中加入以后,就可以显示出来了