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 看着这样的框框是不是很不爽 灭他.也不难.. .如果全部页面都有继承一个自定义的父类 ..那整个项目代码量就只有几行了.. 单 ...
随机推荐
- 我一个二本大学是如何拿到阿里offer的
作者:薛勤,互联网从业者,编程爱好者. 本文首发自公众号:代码艺术(ID:onblog)未经许可,不可转载 01:终于步入大学 我既没有跨过山和大海,也没有穿过人山人海,我就是我,一个普通本科大学生. ...
- Multiple annotations found at this line:- The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
解决办法: 右键所在项目 build path configure build path java build path Add Library server Run time (Apache Tom ...
- Java实现 LeetCode 443 压缩字符串
443. 压缩字符串 给定一组字符,使用原地算法将其压缩. 压缩后的长度必须始终小于或等于原数组长度. 数组的每个元素应该是长度为1 的字符(不是 int 整数类型). 在完成原地修改输入数组后,返回 ...
- centos 7 源码安装openssh
环境:centos 7.1.1503 最小化安装 依赖包下载: yum -y install lrzsz zlib-devel perl gcc pam-devel 1.安装openssl ,选用最 ...
- 案例:DG主库未设置force logging导致备库坏块
DG搭建时,官方文档手册有明确提到要设置数据库为force_logging,防止有nologging操作日志记录不全导致备库应用时出现问题. 虽然是老生常谈的安装规范,但现实中总会遇到不遵守规范的场景 ...
- 05-IntentFilter的匹配规则
IntentFilter的匹配规则 原则上一个Intent不应该既是显示调用又是隐式调用,如果二者共存的话以显式调用为主 隐式调用需要Intent能够匹配目标组件的IntentFilter中所设置的过 ...
- Vue3 新特性
一.vue3 为什么要重写 两个主要原因考虑重写vue新版本主要功能: 1.主流浏览器对新的JavaScript语言特性的普遍支持. 2.当前Vue代码库随着时间的推移而暴露出来的设计和体系架构问题. ...
- Android官方新推的DI库 Hilt
Android官方新推的DI库 Hilt Hilt是Google Android官方新推荐的依赖注入工具. 已加入到官方文档: Dependency injection with Hilt. 目前是a ...
- [转]记一次linux(被)入侵,服务器变矿机~
0x00 背景 周一早上刚到办公室,就听到同事说有一台服务器登陆不上了,我也没放在心上,继续边吃早点,边看币价是不是又跌了.不一会运维的同事也到了,气喘吁吁的说:我们有台服务器被阿里云冻结了,理由:对 ...
- 代码点(code point)和代码单元(code units)
1. 解释一 char:Java中,char类型为16个二进制位,原本用于表示一个字符.但后来发现,16位已经不够表示所有的字符,所以后来发展出了代码点表示字符的方法. 代码点(code point) ...