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 ...
随机推荐
- Linux 学习笔记之超详细基础linux命令 Part 6
Linux学习笔记之超详细基础linux命令 by:授客 QQ:1033553122 ---------------------------------接Part 5----------------- ...
- Flutter 布局(八)- Stack、IndexedStack、GridView详解
本文主要介绍Flutter布局中的Stack.IndexedStack.GridView控件,详细介绍了其布局行为以及使用场景,并对源码进行了分析. 1. Stack A widget that po ...
- Ubuntu16.04升级 Ubuntu18.04
1.更新资源 $ sudo apt-get update $ sudo apt-get upgrade $ sudo apt dist-upgrade 2.安装update-manager-core ...
- 跨站请求伪造(CSRF)
1. 什么是跨站请求伪造(CSRF) CSRF(Cross-site request forgery跨站请求伪造,也被称为“One Click Attack”或者session Riding,通常缩 ...
- vs下开发windows服务程序
一. VS2012下开发Windows服务 1. 打开VS2012,新建项目,选择Windows服务,此处我以开发一个定时自动发送邮件的服务来做介绍,如下图: 2. 创建好后,编译器会自动创建一些文件 ...
- 洗礼灵魂,修炼python(21)--自定义函数(2)—函数文档,doctest模块,形参,实参,默认参数,关键字参数,收集参数,位置参数
函数文档 1.什么是函数文档: 就是放在函数体之前的一段说明,其本身是一段字符串,一个完整的函数需要带有函数文档,这样利于他人阅读,方便理解此函数的作用,能做什么运算 2.怎么查看函数文档: func ...
- Matplotlib:plt.text()给图形添加数据标签
1.数据可视化呈现的最基础图形就是:柱状图.水平条形图.折线图等等: 在python的matplotlib库中分别可用bar.barh.plot函数来构建它们,再使用xticks与yticks(设置坐 ...
- logstash过滤器插件filter详解及实例
1.logstash过滤器插件filter 1.1.grok正则捕获 grok是一个十分强大的logstash filter插件,他可以通过正则解析任意文本,将非结构化日志数据弄成结构化和方便查询的结 ...
- Docker容器学习与分享12
Docker多主机管理 之前在一台Centos7上安装了Docker,如果是在多台主机上都安装Docker,用手动安装的方法不光效率低下,而且有可能出错,所以可以使用Docker Machine进行多 ...
- mybatis使用<choose> <when>
一.需求 后台使用orcale数据库,mybatis做持久层,前台搜索功能,根据类型搜索,但是数据库中没有类型字段, 所以需要在where条件语句中进行判断,当type == x1 时和type == ...