先上代码,不捕获异常和手动捕获异常处理:

@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--异常统一处理的更多相关文章

  1. springBoot异常统一处理

    springBoot异常统一处理 采用@ControllerAdvice注解和@ExceptionHandler注解,可以对异常进行统一处理. 1.结构图: 2.pom.xml文件: <?xml ...

  2. springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务

    springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...

  3. Springboot项目全局异常统一处理

    转自https://blog.csdn.net/hao_kkkkk/article/details/80538955 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项 ...

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

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

  5. springboot返回统一接口与统一异常处理

    springboot返回统一接口与统一异常处理 编写人员:yls 编写时间:2019-9-19 0001-springboot返回统一接口与统一异常处理 简介 创建统一的返回格式 Result 封装统 ...

  6. Springboot项目统一异常处理

    Springboot项目统一异常处理 一.接口返回值封装 1. 定义Result对象,作为通用返回结果封装 2. 定义CodeMsg对象,作为通用状态码和消息封装 二.定义全局异常类 三.定义异常处理 ...

  7. 深度分析:SpringBoot异常捕获与封装处理,看完你学会了吗?

    SpringBoot异常处理 简介 ​ 日常开发过程中,难免有的程序会因为某些原因抛出异常,而这些异常一般都是利用try ,catch的方式处理异常或者throw,throws的方式抛出异常不管.这种 ...

  8. SpringBoot 如何统一后端返回格式?老鸟们都是这样玩的!

    大家好,我是飘渺. 今天我们来聊一聊在基于SpringBoot前后端分离开发模式下,如何友好的返回统一的标准格式以及如何优雅的处理全局异常. 首先我们来看看为什么要返回统一的标准格式? 为什么要对Sp ...

  9. SpringBoot 如何统一后端返回格式

    在前后端分离的项目中后端返回的格式一定要友好,不然会对前端的开发人员带来很多的工作量.那么SpringBoot如何做到统一的后端返回格式呢?今天我们一起来看看. 为什么要对SpringBoot返回统一 ...

  10. Ext.net 异常统一管理,铥掉可恶的 Request Failure

    Ext.net 异常统一管理,铥掉可恶的 Request Failure 看着这样的框框是不是很不爽 灭他.也不难.. .如果全部页面都有继承一个自定义的父类 ..那整个项目代码量就只有几行了.. 单 ...

随机推荐

  1. 【朝夕专刊】RabbitMQ消息的持久化优先级

    欢迎大家阅读<朝夕Net社区技术专刊> 我们致力于.NetCore的推广和落地,为更好的帮助大家学习,方便分享干货,特创此刊!很高兴你能成为忠实读者,文末福利不要错过哦! 上篇文章介绍了R ...

  2. 快速复习C语言 - 1变量与运算符

    变量与运算符 本篇以读者知道 int.char.float.double 等数据类型为前提条件. float 类型注意事项 float 类型数没有办法跟一个数真正比较是否相等,可以定义借助绝对值在一定 ...

  3. Rocket - tilelink - WidthWidget

    https://mp.weixin.qq.com/s/pmJcsRMviJZjMwlwYw6OgA   简单介绍WidthWidget的实现.   ​​   1. 基本介绍   用于设定与上游节点连接 ...

  4. Verilog缺少一个复合数据类型,如C语言中的结构体

    https://mp.weixin.qq.com/s/_9UsgUQv-MfLe8nS938cfQ Verilog中的数据类型(Data Type)是分散的,缺少一个复合数据类型:把多个wire, r ...

  5. Spring Boot笔记(四) springboot 集成 @Scheduled 定时任务

    个人博客网:https://wushaopei.github.io/    (你想要这里多有) 1.在SpringBoot 项目中使用@Scheduled注解执行定时任务: 配置pom.xml 依赖: ...

  6. (Java实现) 洛谷 P1106 删数问题

    题目描述 键盘输入一个高精度的正整数NN(不超过250250位) ,去掉其中任意kk个数字后剩下的数字按原左右次序将组成一个新的正整数.编程对给定的NN和kk,寻找一种方案使得剩下的数字组成的新数最小 ...

  7. Java实现空瓶换汽水

    1 空瓶换汽水 浪费可耻,节约光荣.饮料店节日搞活动:不用付费,用3个某饮料的空瓶就可以换一瓶该饮料.刚好小明前两天买了2瓶该饮料喝完了,瓶子还在.他耍了个小聪明,向老板借了一个空瓶,凑成3个,换了一 ...

  8. Android开发项目中常用到的开源库

    圆形头像 https://github.com/hdodenhof/CircleImageView ButterKnife https://github.com/JakeWharton/butterk ...

  9. 小程序-图片/文件本地缓存,减少CDN流量消耗

    写在前面 小程序网络图片读取: 在读取OSS图片CDN分发时流量大量消耗,导致资金费用增加. 网络图片比较大时,图片加载缓慢. 为了尽量减少上面两个问题,所以对已读的图片进行缓存处理,减少多次访问不必 ...

  10. <VCC笔记> Assumption

    接下来是第二种注释语句类型Assumption.语法_(Assume E), 这个表达式是让VCC在接下来的额推理中,无视表达式E, 直接认可表达式E. 例: int x, y; _(assume x ...