微人事第四天:自定义异常视图
程序员文章站
2022-04-30 22:43:08
...
连按两次shift可以看到在ErrorMvcAutoConfiguration中的 DefaultErrorViewResolve方法是用来处理自定义异常视图的。(生效的条件是我们没有提供自定义异常视图)
@Bean
@ConditionalOnBean({DispatcherServlet.class})
@ConditionalOnMissingBean({ErrorViewResolver.class})
DefaultErrorViewResolver conventionErrorViewResolver() {
return new DefaultErrorViewResolver(this.applicationContext, this.resourceProperties);
}
如果我们不用默认的自定义异常视图,我们需要自己配置一个类。
package org.javaboy.exception;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.DefaultErrorViewResolver;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@Component
public class MyErrorViewResolver extends DefaultErrorViewResolver {
public MyErrorViewResolver(ApplicationContext applicationContext, ResourceProperties resourceProperties) {
super(applicationContext, resourceProperties);
}
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView mv = new ModelAndView();
mv.setViewName("javaboy");
mv.addAllObjects(model);
return mv;
}
}
然后再templates下写一个异常类:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>javaboy-5xx</h1>
<table border="1">
<tr>
<td>path</td>
<td th:text="${path}"></td>
</tr>
<tr>
<td>timestamp</td>
<td th:text="${timestamp}"></td>
</tr>
<tr>
<td>message</td>
<td th:text="${message}"></td>
</tr>
<tr>
<td>error</td>
<td th:text="${error}"></td>
</tr>
<tr>
<td>status</td>
<td th:text="${status}"></td>
</tr>
<tr>
<td>myerror</td>
<td th:text="${myerror}"></td>
</tr>
</table>
</body>
</html>
访问路径:http://localhost:8080/hello
显示: