异常处理最佳实践

根据我的工作经历来看,我主要遵循以下几点:

  1. 尽量不要在代码中写try...catch.finally把异常吃掉。
  2. 异常要尽量直观,防止被他人误解
  3. 将异常分为以下几类,业务异常,登录状态无效异常,(虽已登录,且状态有效)未授权异常,系统异常(JDK中定义Error和Exception,比如NullPointerException, ArithmeticException 和 InputMismatchException)
  4. 可以在某个特定的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;
}
}
}
  1. 使用@ControllerAdvice生命该类中的@ExceptionHandler作用于全局
  2. 使用@ExceptionHandler注册异常处理器,可以注册多个,但是不能重复,比如注册两个方法都用于处理Exception是不行的。
  3. 使用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 ##############################

参考文档

themyleaf 参考文档

异常处理

SpringBoot 异常处理的更多相关文章

  1. SpringBoot异常处理统一封装我来做-使用篇

    SpringBoot异常处理统一封装我来做-使用篇 简介 重复功能我来写.在 SpringBoot 项目里都有全局异常处理以及返回包装等,返回前端是带上succ.code.msg.data等字段.单个 ...

  2. Springboot异常处理和自定义错误页面

    1.异常来源 要处理程序发生的异常,首先需要知道异常来自哪里? 1.前端错误的的请求路径,会使得程序发生4xx错误,最常见的就是404,Springboot默认当发生这种错误的请求路径,pc端响应的页 ...

  3. SpringBoot异常处理(二)

    参数校验机制 JSR-303 Hibernate 参数接收方式: URL路径中的参数 {id} (@PathVariable(name="id") int-whatever) UR ...

  4. 【使用篇二】SpringBoot异常处理(9)

    异常的处理方式有多种: 自定义错误页面 @ExceptionHandler注解 @ControllerAdvice+@ExceptionHandler注解 配置SimpleMappingExcepti ...

  5. springBoot异常处理

    1.status=404 Whitelabel Error Page Whitelabel Error Page This application has no explicit mapping fo ...

  6. SpringBoot学习15:springboot异常处理方式5(通过实现HandlerExceptionResolver类)

    修改异常处理方式4中的全局异常处理controller package com.bjsxt.exception; import org.springframework.context.annotati ...

  7. SpringBoot学习14:springboot异常处理方式4(使用SimpleMappingExceptionResolver处理异常)

    修改异常处理方法3中的全局异常处理Controller即可 package bjsxt.exception; import org.springframework.context.annotation ...

  8. SpringBoot学习13:springboot异常处理方式3(使用@ControllerAdvice+@ExceptionHandle注解)

    问题:使用@ExceptionHandle注解需要在每一个controller代码里面都添加异常处理,会咋成代码冗余 解决方法:新建一个全局异常处理类,添加@ControllerAdvice注解即可 ...

  9. SpringBoot学习12:springboot异常处理方式2(使用@ExceptionHandle注解)

    1.编写controller package com.bjsxt.controller; import org.springframework.stereotype.Controller; impor ...

随机推荐

  1. 【图解】Web前端实现类似Excel的电子表格

    本文将通过图解的方式,使用纯前端表格控件 SpreadJS 来一步一步实现在线的电子表格产品(例如可构建Office 365 Excel产品.Google的在线SpreadSheet). 工具简介: ...

  2. Loadrunner 脚本开发-利用Loadrunner生成Web service测试脚本

    脚本开发-利用Loadrunner生成Web service测试脚本 1.选择协议--Web Service,如下图 2.导入服务 入口1:点击Manage Services ->弹出窗中选择“ ...

  3. Jni 线程JNIEnv,JavaVM,JNI_OnLoad(GetEnv返回NULL?FindClass返回NULL?)

    此文章是关于NDK线程的第二篇理论知识笔记.主要有两个点,如下: 1.pthread_create(Too many arguements, expected 1) ?2.线程中如何获取JNIEnv? ...

  4. python同步原语--线程锁

    多线程锁是python多种同步原语中的其中一种.首先解析一下什么是同步原语,python因为GIL(全局解析锁)的缘故,并没有真正的多线性.另外python的多线程存在一个问题,在多线程编程时,会出现 ...

  5. sass @function,@for,@mixin 的应用

    项目前提: 不同的汽车显示不同的图片,一共9种汽车:每种汽车显示不同状态的图片,一共6种状态,所以一共会有54张图片 后台接口返回汽车种类分别为:1-9,汽车状态分别为:0-5 项目需求: 根据后台返 ...

  6. maven(八),阿里云国内镜像,提高jar包下载速度

    镜像 maven默认会从中央仓库下载jar包,这个仓库在国外,而且全世界的人都会从这里下载,所以下载速度肯定是非常慢的.镜像就相当于是中央仓库的一个副本,内容和中央仓库完全一样,目前有不少国内镜像,其 ...

  7. 06-OpenLDAP密码策略

    阅读视图 openldap密码策略 OpenLDAP服务端定制密码策略 客户端策划策略实例 定义用户第一次登录就修改密码 问题排查手册 重点推荐官方文档 备注:本文依然承接系列文. 1. openld ...

  8. C#语言————第四章 常用Convert类的类型转换方法

    方法 说明Convert.ToInt32() 转换为整型(int 型)Convert.ToStringle() 转换为单精度浮点型(float 型)Convert.ToDouble()  转换为双精度 ...

  9. 传智播客张孝祥java邮件开发随笔01

    01_传智播客张孝祥java邮件开发_课程价值与目标介绍 02_传智播客张孝祥java邮件开发_邮件方面的基本常识 03_传智播客张孝祥java邮件开发_手工体验smtp和pop3协议 第3课时 关于 ...

  10. 安装slide后Powerpoint 不自动退出的解决方案

    症状 打开PPT文件,powerpoint界面不启动. 原因 安装slide之后,powerpoint关闭后,powerpnt.exe进程不正常退出,需要手工终止. 解决方案 打开cmd,进入slid ...