spring boot 异常处理(转)
spring boot在异常的处理中,默认实现了一个EmbeddedServletContainerCustomizer并定义了一个错误页面到”/error”中,在ErrorMvcAutoConfiguration源码中可以看到
/**
* {@link EmbeddedServletContainerCustomizer} that configures the container's error
* pages.
*/
private static class ErrorPageCustomizer
implements EmbeddedServletContainerCustomizer, Ordered {
private final ServerProperties properties;
protected ErrorPageCustomizer(ServerProperties properties) {
this.properties = properties;
}
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(this.properties.getServletPrefix()
+ this.properties.getError().getPath()));
}
@Override
public int getOrder() {
return 0;
}
}
还配置了一个默认的白板页面,在源码可以看到
@Configuration
@ConditionalOnProperty(prefix = "server.error.whitelabel", name = "enabled", matchIfMissing = true)
@Conditional(ErrorTemplateMissingCondition.class)
protected static class WhitelabelErrorViewConfiguration {
private final SpelView defaultErrorView = new SpelView(
"<html><body><h1>Whitelabel Error Page</h1>"
+ "<p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p>"
+ "<div id='created'>${timestamp}</div>"
+ "<div>There was an unexpected error (type=${error}, status=${status}).</div>"
+ "<div>${message}</div></body></html>");
@Bean(name = "error")
@ConditionalOnMissingBean(name = "error")
public View defaultErrorView() {
return this.defaultErrorView;
}
// If the user adds @EnableWebMvc then the bean name view resolver from
// WebMvcAutoConfiguration disappears, so add it back in to avoid disappointment.
@Bean
@ConditionalOnMissingBean(BeanNameViewResolver.class)
public BeanNameViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return resolver;
}
}
在路径的处理上,定义了一个BasicErrorController来处理异常,ErrorAttributes来装载错误异常到前端
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
private final ErrorProperties errorProperties;
//...
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
response.setStatus(getStatus(request).value());
Map<String, Object> model = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.TEXT_HTML));
return new ModelAndView("error", model);
}
@RequestMapping
@ResponseBody
public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
Map<String, Object> body = getErrorAttributes(request,
isIncludeStackTrace(request, MediaType.ALL));
HttpStatus status = getStatus(request);
return new ResponseEntity<Map<String, Object>>(body, status);
}
//...
}
默认只要你请求的content-type是”text/html”则返回一个白版页面给你,如果是其他的content-type,则返回一个json的数据给你。
若你想自定义异常,可以通过以下方式来处理
1.你可以默认在classpath:templates下定义一个error.ftl的freemarker模版来定义异常页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1> error page !! </h1>
${timestamp?string('yyyy-MM-dd HH:mm:ss')}<br/><br/>
${status} <br/><br/>
${error} <br/><br/>
${message} <br/><br/>
${path} <br/><br/>
</body>
</html>
2.可以利用@ExceptionHandler来为某个特定的controller拦截异常,并返回一个json数据,当然你也可以定义全部的controller来拦截异常
@ControllerAdvice(basePackageClasses = FooController.class)
public class FooControllerAdvice extends ResponseEntityExceptionHandler {
@ExceptionHandler(YourException.class)
@ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}
3.还可以自定义server的错误页面
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer(){
return new MyCustomizer();
}
// ...
private static class MyCustomizer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/500"));
}
} <link rel="stylesheet" href="http://csdnimg.cn/release/phoenix/production/markdown_views-0bc64ada25.css">
</div>
spring boot 异常处理(转)的更多相关文章
- Spring Boot 异常处理
Spring Boot 异常处理 本节介绍一下 Spring Boot 启动时是如何处理异常的?核心类是 SpringBootExceptionReporter 和 SpringBootExcepti ...
- Spring Boot异常处理详解
在Spring MVC异常处理详解中,介绍了Spring MVC的异常处理体系,本文将讲解在此基础上Spring Boot为我们做了哪些工作.下图列出了Spring Boot中跟MVC异常处理相关的类 ...
- Spring Boot异常处理
一.默认映射 我们在做Web应用的时候,请求处理过程中发生错误是非常常见的情况.Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局 ...
- Spring boot 异常处理配置
1. 新建Maven项目 exception 2. pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0&quo ...
- Spring Boot 异常处理静止trace
概述 在spring boot 2.2 中 默认状态为status 999 private void addStatus(Map<String, Object> errorAttribut ...
- Spring Boot 知识图谱
最近有意重新学习下SpringBoot知识,特地总结了SpringBoot的知识点,对于想要学习的人来说,够用. SpringBoot学习路径 第一部分:了解 Spring Boot Spring B ...
- 40 篇原创干货,带你进入 Spring Boot 殿堂!
两个月前,松哥总结过一次已经完成的 Spring Boot 教程,当时感受到了小伙伴们巨大的热情. 两个月过去了,松哥的 Spring Boot 教程又更新了不少,为了方便小伙伴们查找,这里再给大家做 ...
- Spring Boot 日志处理你还在用Logback?
▶ Log4j2 性能 https://logging.apache.org/log4j/2.x/performance.html ▶ Spring Boot 依赖与配置 Maven 依赖 <! ...
- 天天玩微信,Spring Boot 开发私有即时通信系统了解一下
1/ 概述 利用Spring Boot作为基础框架,Spring Security作为安全框架,WebSocket作为通信框架,实现点对点聊天和群聊天. 2/ 所需依赖 Spring Boot 版本 ...
随机推荐
- typeof 、Object.prototype.toString和 instanceof
数据类型 js 基本类型包括:Undefined symbol null string boolean number js 引用类型包括:object array Date RegExp typeo ...
- Could not resolve placeholder 'CUST_INDUSTORY' in string value "${CUST_INDUSTORY}"
问题描述 项目中的资源文件中写了个properties文件,内容这样的 CUST_FROM=002 CUST_INDUSTORY=001 CUST_LEVEL=006 在springmvc配置文件中加 ...
- Angular+Bootstrap3导航菜单
Angular+Bootstrap3导航菜单 AngularJS体验式编程系列文章,将介绍如何用angularjs构建一个强大的web前端系统.angularjs是由Google团队开发的一款非常优秀 ...
- C/C++常考基础面试题(更新)
题目来自牛客网 解析部分来自牛客网 https://www.nowcoder.com/4685265 一 分析下面代码有什么问题? void test1() { char string[10]; ch ...
- Windows中使用CopyFile函数复制文件,出现string转LPCTSTR问题(附代码)
原因: 同一张图片,用imread读取,imwrite重新写入另外一个文件夹,然后再次读取发现前后异常,这是因为读取后转成Mat格式,然后写入转成图片格式,这个过程会对图片产生损失. 因此后来采用直接 ...
- Spring AOP(三)--XML方式实现
本文介绍通过XML方式实现Spring AOP,在上一篇中已经介绍了通过注解+java配置的方式,这篇文章主要是看XML中怎么配置,直接上代码了: 一.创建一个连接点 1⃣️定义接口 注意⚠️:可以定 ...
- YUM配置文件
创建容器,位置在/etc/yum.repos.d,扩展名必须是.repo #cd /etc/yum.repos.d #vim yum.repo 新建一个仓库文件,名字可以随便定义,在 ...
- (5)连续非周期信号的傅里叶变换(频谱) & 周期信号的傅里叶变换
参考资料:<信号与系统(第二版)> 杨晓非 何丰 从傅里叶级数到傅里叶变换 通过分析连续周期信号的周期与频谱的关系,当周期趋于无穷大的时候,周期信号变成非周期信号.从频谱分析观点来看,当T ...
- HDU5412 CRB and Queries 整体二分
传送门 刚觉得最近写代码比较顺畅没什么Bug,cdq分治真是我的一个噩梦.. 整体二分模板题,带修改的区间第k小. vjudge不知抽什么风,用不了,hdu忘了密码了一直在那里各种试,难受.. 写得比 ...
- Visual Studio 2019 正式发布
原文链接: https://www.oschina.net/news/105629/vs2019-general-availability 如约而至,微软已于今天推出 Visual Studio 20 ...