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 看着这样的框框是不是很不爽 灭他.也不难.. .如果全部页面都有继承一个自定义的父类 ..那整个项目代码量就只有几行了.. 单 ...
随机推荐
- Java实现 LeetCode 815 公交路线(创建关系+BFS)
815. 公交路线 我们有一系列公交路线.每一条路线 routes[i] 上都有一辆公交车在上面循环行驶.例如,有一条路线 routes[0] = [1, 5, 7],表示第一辆 (下标为0) 公交车 ...
- Java实现蓝桥杯 算法提高 线段和点
算法提高 线段和点 时间限制:1.0s 内存限制:256.0MB 提交此题 问题描述 有n个点和m个区间,点和区间的端点全部是整数,对于点a和区间[b,c],若a>=b且a<=c,称点a满 ...
- Java实现 蓝桥杯 算法训练 动态数组使用
算法训练 动态数组使用 时间限制:1.0s 内存限制:512.0MB 提交此题 从键盘读入n个整数,使用动态数组存储所读入的整数,并计算它们的和与平均值分别输出.要求尽可能使用函数实现程序代码.平均值 ...
- Java实现 LeetCode 368 最大整除子集
368. 最大整除子集 给出一个由无重复的正整数组成的集合,找出其中最大的整除子集,子集中任意一对 (Si,Sj) 都要满足:Si % Sj = 0 或 Sj % Si = 0. 如果有多个目标子集, ...
- Java实现 LeetCode 21 合并两个有序链表
21. 合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两个链表的所有节点组成的. 示例: 输入:1->2->4, 1->3->4 输出:1 ...
- java实现第三届蓝桥杯古代赌局
古代赌局 [编程题](满分23分) 俗话说:十赌九输.因为大多数赌局的背后都藏有阴谋.不过也不尽然,有些赌局背后藏有的是:"阳谋". 有一种赌局是这样的:桌子上放六个匣子,编号是1 ...
- 美女面试官问我Python如何优雅的创建临时文件,我的回答....
[摘要] 本故事纯属虚构,如有巧合,他们故事里的美女面试官也肯定没有我的美,请自行脑补... 小P像多数Python自学者一样,苦心钻研小半年,一朝出师投简历. 这不,一家招聘初级Python开发工程 ...
- Android getMeasuredHeight()与getHeight()的区别
getMeasuredHeight()返回的是原始测量高度,与屏幕无关 getHeight()返回的是在屏幕上显示的高度 实际上在当屏幕可以包裹内容的时候,他们的值是相等的,只有当view超出屏幕后, ...
- 手把手教你用redis实现一个简单的mq消息队列(java)
众所周知,消息队列是应用系统中重要的组件,主要解决应用解耦,异步消息,流量削锋等问题,实现高性能,高可用,可伸缩和最终一致性架构.目前使用较多的消息队列有 ActiveMQ,RabbitMQ,Zero ...
- kafka基本概念和hello world搭建
什么是kafka? Kafka是由Apache软件基金会开发的一个开源流处理平台,由Scala和Java编写.Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者在网站中的所有动作流数据 ...