SpringBoot 异常处理
异常处理最佳实践
根据我的工作经历来看,我主要遵循以下几点:
- 尽量不要在代码中写try...catch.finally把异常吃掉。
- 异常要尽量直观,防止被他人误解
- 将异常分为以下几类,业务异常,登录状态无效异常,(虽已登录,且状态有效)未授权异常,系统异常(JDK中定义Error和Exception,比如NullPointerException, ArithmeticException 和 InputMismatchException)
- 可以在某个特定的Controller中处理异常,也可以使用全局异常处理器。尽量使用全局异常处理器
使用@ControllerAdvice注释全局异常处理器
@ControllerAdvice
public class GlobalExceptionHandler implements ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@ExceptionHandler
public Object businessExceptionHandler(Exception exception, HttpServletRequest req) {
DtoResult response = new DtoResult();
if (exception instanceof BusinessException) {
int code = ((BusinessException) exception).getErrorCode();
response.setCode(code > 0 ? code : DtoResult.STATUS_CODE_BUSINESS_ERROR);
response.setMessage(exception.getMessage());
} else if (exception instanceof NotAuthorizedException) {
response.setCode(DtoResult.STATUS_CODE_NOT_AUTHORIZED);
response.setMessage(exception.getMessage());
} else {
response.setCode(DtoResult.STATUS_CODE_SYSTEM_ERROR);
String profile = applicationContext.getEnvironment().getProperty("spring.profiles.active");
if (profile != GlobalConst.PROFILE_PRD) {
response.setMessage(exception.toString());
} else {
response.setMessage("系统异常");
}
logger.error("「系统异常」", exception);
}
String contentTypeHeader = req.getHeader("Content-Type");
String acceptHeader = req.getHeader("Accept");
String xRequestedWith = req.getHeader("X-Requested-With");
if ((contentTypeHeader != null && contentTypeHeader.contains("application/json"))
|| (acceptHeader != null && acceptHeader.contains("application/json"))
|| "XMLHttpRequest".equalsIgnoreCase(xRequestedWith)) {
HttpStatus httpStatus = HttpStatus.OK;
if (response.getCode() == DtoResult.STATUS_CODE_SYSTEM_ERROR) {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
}
return new ResponseEntity<>(response, httpStatus);
} else {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("detailMessage", response.getMessage());
modelAndView.addObject("url", req.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
}
}
- 使用@ControllerAdvice生命该类中的@ExceptionHandler作用于全局
- 使用@ExceptionHandler注册异常处理器,可以注册多个,但是不能重复,比如注册两个方法都用于处理Exception是不行的。
- 使用HttpServletRequest中的header检测请求是否为ajax, 如果是ajax则返回json(即ResponseEnttiy<>), 如果为非ajax则返回view(即ModelAndView)
thymeleaf模板标签解析错误
themyleaf默认使用HTML5模式,此模式比较严格,比如当标签没有正常闭合,属性书写不正确时都会报错,比如以下格式
# meta标签没有闭合
<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>程序出错了 - 智联</title>
</head>
<body>
<p>程序出错了...</p>
<p>请求地址:<span th:text="${url}"></span></p>
<p>详情:<span th:text="${detailMessage}"></span></p>
</body>
</html>
# 属性v-cloak不符合格式
<div v-cloak></div>
解决方法
可以在配置文件中增加 spring.thymeleaf.mode=LEGACYHTML5 配置项,默认情况下是 spring.thymeleaf.mode=HTML5,
LEGACYHTML5 需要搭配第三方库 nekohtml 才可以使用。
# 1.在 pom.xml 中增加如下内容:
<!-- https://mvnrepository.com/artifact/net.sourceforge.nekohtml/nekohtml -->
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
# 2.修改 application.properties 为:
############################## thymeleaf ##############################
spring.thymeleaf.cache=false
# spring.thymeleaf.mode=HTML5
spring.thymeleaf.mode=LEGACYHTML5
############################## thymeleaf ##############################
参考文档
- SpringBoot系列学习十:统一异常处理
- @ExceptionHandler for Ajax and non-Ajax
- Spring MVC
- Spring MVC @ExceptionHandler Example
- Spring Boot中Web应用的统一异常处理
- Spring MVC View Resolver
- Exception Handling in Spring MVC
- Spring: RESTful controllers and error handling
themyleaf 参考文档
异常处理
SpringBoot 异常处理的更多相关文章
- SpringBoot异常处理统一封装我来做-使用篇
SpringBoot异常处理统一封装我来做-使用篇 简介 重复功能我来写.在 SpringBoot 项目里都有全局异常处理以及返回包装等,返回前端是带上succ.code.msg.data等字段.单个 ...
- Springboot异常处理和自定义错误页面
1.异常来源 要处理程序发生的异常,首先需要知道异常来自哪里? 1.前端错误的的请求路径,会使得程序发生4xx错误,最常见的就是404,Springboot默认当发生这种错误的请求路径,pc端响应的页 ...
- SpringBoot异常处理(二)
参数校验机制 JSR-303 Hibernate 参数接收方式: URL路径中的参数 {id} (@PathVariable(name="id") int-whatever) UR ...
- 【使用篇二】SpringBoot异常处理(9)
异常的处理方式有多种: 自定义错误页面 @ExceptionHandler注解 @ControllerAdvice+@ExceptionHandler注解 配置SimpleMappingExcepti ...
- springBoot异常处理
1.status=404 Whitelabel Error Page Whitelabel Error Page This application has no explicit mapping fo ...
- SpringBoot学习15:springboot异常处理方式5(通过实现HandlerExceptionResolver类)
修改异常处理方式4中的全局异常处理controller package com.bjsxt.exception; import org.springframework.context.annotati ...
- SpringBoot学习14:springboot异常处理方式4(使用SimpleMappingExceptionResolver处理异常)
修改异常处理方法3中的全局异常处理Controller即可 package bjsxt.exception; import org.springframework.context.annotation ...
- SpringBoot学习13:springboot异常处理方式3(使用@ControllerAdvice+@ExceptionHandle注解)
问题:使用@ExceptionHandle注解需要在每一个controller代码里面都添加异常处理,会咋成代码冗余 解决方法:新建一个全局异常处理类,添加@ControllerAdvice注解即可 ...
- SpringBoot学习12:springboot异常处理方式2(使用@ExceptionHandle注解)
1.编写controller package com.bjsxt.controller; import org.springframework.stereotype.Controller; impor ...
随机推荐
- Kotlin入门(7)循环语句的操作
上一篇文章介绍了简单分支与多路分支的实现,控制语句除了这两种条件分支之外,还有对循环处理的控制,那么本文接下来继续阐述Kotlin如何对循环语句进行操作. Koltin处理循环语句依旧采纳了for和w ...
- (后台)Java:对double值进行四舍五入,保留两位小数的几种方法
mport java.text.DecimalFormat; DecimalFormat df = new DecimalFormat("######0.00"); double ...
- JavaScript大杂烩9 - 理解BOM
毫无疑问,我们学习JavaScript是为了完成特定的功能.在最初的JavaScript类型系统中,我们已经分析过JavaScript在页面开发中充当着添加逻辑的角色,而且我们知道JavaScript ...
- 泛化之美--C++11可变模版参数的妙用
1概述 C++11的新特性--可变模版参数(variadic templates)是C++11新增的最强大的特性之一,它对参数进行了高度泛化,它能表示0到任意个数.任意类型的参数.相比C++98/03 ...
- TinyEditor
今天在github 上看到一个非常巧妙的项目:umpox/TinyEditor 使用简单的浏览器就能构造一个简单的实时运行代码的基于浏览器的前端编辑器,只需要很少代码: 使用方法: 粘贴如下代码到浏览 ...
- [MapReduce_add_1] Windows 下开发 MapReduce 程序部署到集群
0. 说明 Windows 下开发 MapReduce 程序部署到集群 1. 前提 在本地开发的时候保证 resource 中包含以下配置文件,从集群的配置文件中拷贝 在 resource 中新建 ...
- Django框架的使用教程--Cookie-Session[五]
Cookie cookie是存储在浏览器中的一段文本信息,下次同一网站请求,就会发送该cookie给服务器,一般的浏览器都有启动cookie,用cookie存储信息,最好不要存储密码,cookie也有 ...
- MDX 脚本语句 -- Scope
在多维表达式 (MDX) 中,下列语句用于管理 MDX 脚本中的上下文.作用域和流控制. 主题 说明 calculate语句 计算子多维数据集,还可以确定子多维数据集中所包含的求解次序 case语句 ...
- January 04th, 2018 Week 01st Thursday
Just do what works for you, because there will always be someone who think differently. 就做你自己所能做的,因为 ...
- indexOf() 使用方法(数组去重)
对于indexOf()的用法一直停留在查找第几个字符串,却不知道它能用到数组去重中,首先还是温顾下indexOf()的语法: <!DOCTYPE html> <html lang=& ...