Spring Boot2 系列教程 (十四) | 统一异常处理
如题,今天介绍 SpringBoot 是如何统一处理全局异常的。SpringBoot 中的全局异常处理主要起作用的两个注解是 @ControllerAdvice 和 @ExceptionHandler ,其中 @ControllerAdvice 是组件注解,添加了这个注解的类能够拦截 Controller 的请求,而 ExceptionHandler 注解可以设置全局处理控制里的异常类型来拦截要处理的异常。 比如:@ExceptionHandler(value = NullPointException.class) 。
准备工作
- SpringBoot 2.1.3
- IDEA
- JDK 8
依赖配置
<dependencies>
<!-- JPA 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- mysql 连接类 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- lombok 依赖 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 单元测试依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
配置文件
spring:
# 数据库相关
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update #ddl-auto:设为 create 表示每次都重新建表
show-sql: true
返回的消息类
public class Message<T> implements Serializable {
/**
* 状态码
*/
private Integer code;
/**
* 返回信息
*/
private String message;
/**
* 返回的数据类
*/
private T data;
/**
* 时间
*/
private Long time;
// getter、setter 以及 构造方法略。。。
}
工具类
用于处理返回的数据以及信息类,代码注释很详细不说了。
public class MessageUtil {
/**
* 成功并返回数据实体类
* @param o
* @param <E>
* @return
*/
public static <E>Message<E> ok(E o){
return new Message<>(200, "success", o, new Date().getTime());
}
/**
* 成功,但无数据实体类返回
* @return
*/
public static <E>Message<E> ok(){
return new Message<>(200, "success", null, new Date().getTime());
}
/**
* 失败,有自定义异常返回
* @param code
* @param msg
* @return
*/
public static <E>Message<E> error(Integer code,String msg){
return new Message<>(code, msg, null, new Date().getTime());
}
}
自定义异常
通过继承 RuntimeException ,声明 code 用于定义不同类型的自定义异常。主要是用于异常拦截出获取 code 并将 code 设置到消息类中返回。
public class CustomException extends RuntimeException{
/**
* 状态码
*/
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public CustomException(Integer code, String message){
super(message);
this.code = code;
}
}
异常拦截类
通过加入 @RestControllerAdvice 来声明该类可拦截 Controller 请求,同时在 handle方法加入 @ExceptionHandler 并在该注解中指定要拦截的异常类。
@RestControllerAdvice // 控制器增强处理(返回 JSON 格式数据),添加了这个注解的类能被 classpath 扫描自动发现
public class ExceptionHandle {
@ExceptionHandler(value = Exception.class) // 捕获 Controller 中抛出的指定类型的异常,也可以指定其他异常
public <E>Message<E> handler(Exception exception){
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else {
return MessageUtil.error(120, "异常信息:" + exception.getMessage());
}
}
}
这里只对自定义异常以及未知异常进行处理,如果你在某方法中明确知道可能会抛出某个异常,可以加多一个特定的处理。比如说你明确知道该方法可能抛出 NullPointException 可以追加 NullPointException 的处理:
if (exception instanceof CustomException){
CustomException customException = (CustomException) exception;
return MessageUtil.error(customException.getCode(), customException.getMessage());
} else if (exception instanceof NullPointException ){
return MessageUtil.error(500, "空指针异常信!");
} else {
return MessageUtil.error(120, "异常信息:" + exception.getMessage());
}
controller 层
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@GetMapping("/{id}")
public Message<Student> findStudentById(@PathVariable("id") Integer id){
if (id < 0){
//测试自定义错误
throw new CustomException(110, "参数不能是负数!");
} else if (id == 0){
//硬编码,为了测试
Integer i = 1/id;
return null;
} else {
Student student = studentService.findStudentById(id);
return MessageUtil.ok(student);
}
}
}
完整代码
https://github.com/turoDog/Demo/tree/master/springboot_exception_demo
如果觉得对你有帮助,请给个 Star 再走呗,非常感谢。
Postman 测试
访问 http://localhost:8080/student/5 测试正常返回数据结果。
访问 http://localhost:8080/student/0 测试未知异常的结果。
访问 http://localhost:8080/student/-11 测试自定义异常的结果。
最后
如果看到这里,说明你喜欢这篇文章,请转发、点赞。微信搜索「一个优秀的废人」,关注后回复「1024」送你一套完整的 java 教程。
Spring Boot2 系列教程 (十四) | 统一异常处理的更多相关文章
- Spring Boot2 系列教程(十四)CORS 解决跨域问题
今天和小伙伴们来聊一聊通过CORS解决跨域问题. 同源策略 很多人对跨域有一种误解,以为这是前端的事,和后端没关系,其实不是这样的,说到跨域,就不得不说说浏览器的同源策略. 同源策略是由 Netsca ...
- Spring Boot2 系列教程(十)Spring Boot 整合 Freemarker
今天来聊聊 Spring Boot 整合 Freemarker. Freemarker 简介 这是一个相当老牌的开源的免费的模版引擎.通过 Freemarker 模版,我们可以将数据渲染成 HTML ...
- Spring Boot2 系列教程 (十) | 实现声明式事务
前言 如题,今天介绍 SpringBoot 的 声明式事务. Spring 的事务机制 所有的数据访问技术都有事务处理机制,这些技术提供了 API 用于开启事务.提交事务来完成数据操作,或者在发生错误 ...
- Spring Boot2 系列教程(十二)@ControllerAdvice 的三种使用场景
严格来说,本文并不算是 Spring Boot 中的知识点,但是很多学过 SpringMVC 的小伙伴,对于 @ControllerAdvice 却并不熟悉,Spring Boot 和 SpringM ...
- Spring Boot2 系列教程(十八)Spring Boot 中自定义 SpringMVC 配置
用过 Spring Boot 的小伙伴都知道,我们只需要在项目中引入 spring-boot-starter-web 依赖,SpringMVC 的一整套东西就会自动给我们配置好,但是,真实的项目环境比 ...
- Spring Boot2 系列教程(十九)Spring Boot 整合 JdbcTemplate
在 Java 领域,数据持久化有几个常见的方案,有 Spring 自带的 JdbcTemplate .有 MyBatis,还有 JPA,在这些方案中,最简单的就是 Spring 自带的 JdbcTem ...
- Spring Boot2 系列教程 (十八) | 整合 MongoDB
微信公众号:一个优秀的废人.如有问题,请后台留言,反正我也不会听. 前言 如题,今天介绍下 SpringBoot 是如何整合 MongoDB 的. MongoDB 简介 MongoDB 是由 C++ ...
- Spring Boot2 系列教程 (十五) | 服务端参数校验之一
估计很多朋友都认为参数校验是客户端的职责,不关服务端的事.其实这是错误的,学过 Web 安全的都知道,客户端的验证只是第一道关卡.它的参数验证并不是安全的,一旦被有心人抓到可乘之机,他就可以有各种方法 ...
- Spring Boot2 系列教程 (十二) | 整合 thymeleaf
前言 如题,今天介绍 Thymeleaf ,并整合 Thymeleaf 开发一个简陋版的学生信息管理系统. SpringBoot 提供了大量模板引擎,包含 Freemarker.Groovy.Thym ...
随机推荐
- laravel构造函数和中间件执行顺序问题
今天想重构下代码结构: BaseController.php 放置公共的中间件 class BaseController { public function __construct(){ $this- ...
- Vue之webpack的entry和output
一.文件结构 二.index.html <!DOCTYPE html> <html lang="en"> <head> <meta cha ...
- 代码片段 Powershell修改桌面壁纸
其实只不过是利用了win32函数 function Set-Wallpaper($image){ $source = @" using System; using System.Runtim ...
- C# “不支持给定路径的格式”异常处理
问题背景 无聊研究了一下怎么发送邮件(包含附件),但发现附带的文件路径除了报错就是报错,不知道为什么. 用了不下好几种方式,比如 var x = "E:\\Git\\cmd\\git.exe ...
- 2019-10-18-WPF-高速书写-StylusPlugIn-原理
title author date CreateTime categories WPF 高速书写 StylusPlugIn 原理 lindexi 2019-10-18 21:23:46 +0800 2 ...
- H3C VLAN基本配置
- WPF 分页控件Pager
本文为伪原创原文为 NET未来之路的https://www.cnblogs.com/lonelyxmas/p/10641255.html 原文中,页码数量会不断增加,会将下一页的按钮顶出去 修改了一下 ...
- 【k8s】kubeadm快速部署Kubernetes
1.Kubernetes 架构图 kubeadm是官方社区推出的一个用于快速部署kubernetes集群的工具. 这个工具能通过两条指令完成一个kubernetes集群的部署: # 创建一个 Mast ...
- python 实现整数的反转:给定一个整数,将该数按位逆置,例如给定12345变成54321,12320变成2321.
给定一个n位(不超过10)的整数,将该数按位逆置,例如给定12345变成54321,12320变成2321. # 第一种方法,使用lstrip函数去反转后,数字前面的0 import math num ...
- HRegion 分配与寻址
1.Region 分配 HMaster负责为Region 分配Region Server,一个Region 只能分配给一个Region server. HMaster中 记录: 哪些Regio ...