SpringBoot--异常统一处理
先上代码,不捕获异常和手动捕获异常处理:
@GetMapping("/error1")
public String error1() {
int i = 10 / 0;
return "test1";
} @ResponseBody
@GetMapping("/error2")
public Map<String, String> error2() {
Map<String, String> result = new HashMap<>(16);
try{
int i = 10 / 0;
result.put("code", "200");
result.put("data", "具体返回的结果集");
} catch (Exception e) {
result.put("code", "500");
result.put("message", "请求错误");
}
return result;
}
其中的各种问题就不再多说了,由于各种问题,因此需要对异常进行统一捕获
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、自定义异常类
package com.example.demo.entity; import lombok.Data; @Data
public class ErrorResponse {
private int code;
private String message; public ErrorResponse(int code, String message) {
this.code = code;
this.message = message;
} public ErrorResponse() { } public ErrorResponse OK(String message){
this.code = 200;
this.message = message;
return this;
} public void OK(){
this.code = 200;
this.message = "";
}
}
3、定义异常模板
package com.example.demo.entity; import lombok.Data; @Data
public class ErrorResponse {
private int code;
private String message; public ErrorResponse(int code, String message) {
this.code = code;
this.message = message;
}
}
4、异常拦截器
此步时重点,需要特殊说明一下,
@ControllerAdvice 捕获 Controller 层抛出的异常,如果添加 @ResponseBody 返回信息则为JSON 格式。
@RestControllerAdvice 相当于 @ControllerAdvice 与 @ResponseBody 的结合体。
@ExceptionHandler 统一处理一种类的异常,减少代码重复率,降低复杂度。 创建一个 GlobalExceptionHandler 类,并添加上 @RestControllerAdvice 注解就可以定义出异常通知类了,然后在定义的方法中添加上 @ExceptionHandler 即可实现异常的捕捉…
package com.example.demo.utils; import com.example.demo.entity.ErrorResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; @RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(LclException.class)
public ErrorResponse lclExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response){
response.setStatus(HttpStatus.BAD_REQUEST.value());
LclException exception = (LclException) e;
return new ErrorResponse(exception.getCode(),exception.getMessage());
} @ExceptionHandler(RuntimeException.class)
public ErrorResponse runtimeExcetionHandler(HttpServletRequest request, final Exception e,HttpServletResponse response){
response.setStatus(HttpStatus.BAD_REQUEST.value());
RuntimeException exception = (RuntimeException) e;
return new ErrorResponse(400,exception.getMessage());
} @Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
if(ex instanceof MethodArgumentNotValidException){
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
return new ResponseEntity<>(new ErrorResponse(status.value(),exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()), status);
} if(ex instanceof MethodArgumentTypeMismatchException){
MethodArgumentTypeMismatchException exception = (MethodArgumentTypeMismatchException) ex;
return new ResponseEntity<>(new ErrorResponse(status.value(),"参数转换异常"),status);
} return new ResponseEntity<>(new ErrorResponse(status.value(), "参数转换异常"), status);
} }
5、测试类
@ResponseBody
@GetMapping("/error3")
public ErrorResponse error3(Integer num) throws LclException{
if(num == null){
throw new LclException(12345,"num不允许为空");
}
int i = 10/num;
return (new ErrorResponse()).OK(i+"");
}
6、测试
SpringBoot--异常统一处理的更多相关文章
- springBoot异常统一处理
springBoot异常统一处理 采用@ControllerAdvice注解和@ExceptionHandler注解,可以对异常进行统一处理. 1.结构图: 2.pom.xml文件: <?xml ...
- springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务
springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...
- Springboot项目全局异常统一处理
转自https://blog.csdn.net/hao_kkkkk/article/details/80538955 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项 ...
- SpringBoot异常处理统一封装我来做-使用篇
SpringBoot异常处理统一封装我来做-使用篇 简介 重复功能我来写.在 SpringBoot 项目里都有全局异常处理以及返回包装等,返回前端是带上succ.code.msg.data等字段.单个 ...
- springboot返回统一接口与统一异常处理
springboot返回统一接口与统一异常处理 编写人员:yls 编写时间:2019-9-19 0001-springboot返回统一接口与统一异常处理 简介 创建统一的返回格式 Result 封装统 ...
- Springboot项目统一异常处理
Springboot项目统一异常处理 一.接口返回值封装 1. 定义Result对象,作为通用返回结果封装 2. 定义CodeMsg对象,作为通用状态码和消息封装 二.定义全局异常类 三.定义异常处理 ...
- 深度分析:SpringBoot异常捕获与封装处理,看完你学会了吗?
SpringBoot异常处理 简介 日常开发过程中,难免有的程序会因为某些原因抛出异常,而这些异常一般都是利用try ,catch的方式处理异常或者throw,throws的方式抛出异常不管.这种 ...
- SpringBoot 如何统一后端返回格式?老鸟们都是这样玩的!
大家好,我是飘渺. 今天我们来聊一聊在基于SpringBoot前后端分离开发模式下,如何友好的返回统一的标准格式以及如何优雅的处理全局异常. 首先我们来看看为什么要返回统一的标准格式? 为什么要对Sp ...
- SpringBoot 如何统一后端返回格式
在前后端分离的项目中后端返回的格式一定要友好,不然会对前端的开发人员带来很多的工作量.那么SpringBoot如何做到统一的后端返回格式呢?今天我们一起来看看. 为什么要对SpringBoot返回统一 ...
- Ext.net 异常统一管理,铥掉可恶的 Request Failure
Ext.net 异常统一管理,铥掉可恶的 Request Failure 看着这样的框框是不是很不爽 灭他.也不难.. .如果全部页面都有继承一个自定义的父类 ..那整个项目代码量就只有几行了.. 单 ...
随机推荐
- Alpha冲刺 —— 5.8
这个作业属于哪个课程 软件工程 这个作业要求在哪里 团队作业第五次--Alpha冲刺 这个作业的目标 Alpha冲刺 作业正文 正文 github链接 项目地址 其他参考文献 无 一.会议内容 1.展 ...
- AUTOSAR-PDU&SDU
https://mp.weixin.qq.com/s/TZcJcHVnNARMcUac2Es0wQ PDU: Protocol Data Unit The PDU contains SDU and ...
- JVM虚拟机 与 GC 垃圾回收
个人博客网:https://wushaopei.github.io/ (你想要这里多有) 一.JVM体系结构概述 1.JVM 与系统.硬件 JVM是运行在操作系统之上的,它与硬件没有直接的交 ...
- 分布式事务专题笔记(三)分布式事务解决方案之TCC(三阶段提交)
个人博客网:https://wushaopei.github.io/ (你想要这里多有) 1.什么是TCC事务 TCC是Try.Confifirm.Cancel三个词语的缩写,TCC要求每个分支 ...
- Java实现 LeetCode 707 设计链表(环形链表)
707. 设计链表 设计链表的实现.您可以选择使用单链表或双链表.单链表中的节点应该具有两个属性:val 和 next.val 是当前节点的值,next 是指向下一个节点的指针/引用.如果要使用双向链 ...
- Java实现 LeetCode 414 第三大的数
414. 第三大的数 给定一个非空数组,返回此数组中第三大的数.如果不存在,则返回数组中最大的数.要求算法时间复杂度必须是O(n). 示例 1: 输入: [3, 2, 1] 输出: 1 解释: 第三大 ...
- Java实现 蓝桥杯VIP 算法训练 友好数
有两个整数,如果每个整数的约数和(除了它本身以外)等于对方,我们就称这对数是友好的.例如: 9的约数和有:1+3=4 4的约数和有:1+2=3 所以9和4不是友好的. 220的约数和有:1 2 4 5 ...
- Java实现 蓝桥杯VIP 算法提高 3-3求圆面积表面积体积
算法提高 3-3求圆面积表面积体积 时间限制:1.0s 内存限制:256.0MB 问题描述 接受用户输⼊的数值,输出以该值为半径的(1)圆面积,(2)球体表面积,(3)球体体积.pi 取值3.1415 ...
- 第八届蓝桥杯JavaB组国(决)赛真题
解题代码部分来自网友,如果有不对的地方,欢迎各位大佬评论 题目1.平方十位数 题目描述 由0~9这10个数字不重复.不遗漏,可以组成很多10位数字. 这其中也有很多恰好是平方数(是某个数的平方). 比 ...
- java算法集训代码填空题练习3
1 数组转置 编写程序将2行3列的数组行列置换复制给3行2列的数组(即数组的转置).已经写了如下代码,请完善之: class y{ public static void main(String[] a ...