SpringBoot配置错误信息页面
放置错误页面到目录中
在resources
的public
或templates
或static
目录下新建error
目录,
将错误页面放入其中,页面的名称以状态码的名称起.
例如404.html
或404.jsp
等
返回的错误信息:
{
"timestamp": "2019-01-27T04:10:20.348+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/123"
}
自定义处理页面
自定义可自己根据错误状态码,定义需要返回的页面.向页面返回的数据与前面是一致的.
但是可自行更改
@Component
public class MyErrorViewResolver implements ErrorViewResolver {
@Override
public ModelAndView resolveErrorView(HttpServletRequest request, HttpStatus status, Map<String, Object> model) {
ModelAndView modelAndView = new ModelAndView();
if (status.is1xxInformational()) {
modelAndView.setViewName("error/1XX");
} else if (status.is2xxSuccessful()) {
modelAndView.setViewName("error/2XX");
} else if (status.is3xxRedirection()) {
modelAndView.setViewName("error/3XX");
} else if (status.is4xxClientError()) {
modelAndView.setViewName("error/4XX");
} else if (status.is5xxServerError()) {
modelAndView.setViewName("error/5XX");
}
modelAndView.getModel().putAll(model);
return modelAndView;
}
}
非SpringMVC环境
@Configuration
public class MyErrorViewResolver implements ErrorPageRegistrar {
@Bean
public ErrorPageRegistrar errorPageRegistrar(){
return new MyErrorPageRegistrar();
}
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
registry.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/400"));
}
}