# Exception_Auto_Demo **Repository Path**: phoenix_legend/exception_-auto_-demo ## Basic Information - **Project Name**: Exception_Auto_Demo - **Description**: 自定义异常类与响应类案例总结代码demo - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2025-08-11 - **Last Updated**: 2025-08-11 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ![输入图片说明](https://foruda.gitee.com/images/1727520608702700327/0026cc39_1469131.png "屏幕截图") ![输入图片说明](https://foruda.gitee.com/images/1727520720717189479/3229d150_1469131.png "屏幕截图") 原文地址:[《Spring Boot应用进阶:打造优雅的错误处理机制与全局异常拦截器》](https://blog.csdn.net/weixin_43891901/article/details/142619632?spm=1001.2014.3001.5501) > 本文主要介绍自己在工作中在处理抛出异常类和封装响应类处理的模板总结。 **对于后端程序员来说,抛出异常和返回响应别提有多重要了对吧。其实在真正的企业级开发中,这步工作也不需要你去做,公司都给你封装好了的,你直接用就行。由于我最近从0到1负责了一个完整的项目,在最近的后期优化过程中,我需要考虑重新设计 自定义异常类与统一响应,所以特此总结该文,以供学习。** ## 自定义异常类AppException 自定义异常类`AppException`需要继承至 `RuntimeException`运行时异常。 ```java public class AppException extends RuntimeException{ private int code = 500; private String msg = "服务器异常"; public AppException(AppExceptionCodeMsg appExceptionCodeMsg){ super(); this.code = appExceptionCodeMsg.getCode(); this.msg = appExceptionCodeMsg.getMsg(); } public AppException(int code,String msg){ super(); this.code = code; this.msg = msg; } public int getCode() { return code; } public String getMsg() { return msg; } } ``` ## 封装业务有关的枚举类AppExceptionCodeMsg 利用枚举类将常用的业务异常进行配置,封装: ```java INVALID_CODE(10000,"验证码无效"), USERNAME_NOT_EXISTS(10001,"用户名不存在"), USER_CREDIT_NOT_ENOUTH(10002,"用户积分不足"); ``` 这样做的好处是,配置灵活,不需要去硬编码。 完整的枚举类如下: ```java //这个枚举类中定义的都是跟业务有关的异常 public enum AppExceptionCodeMsg { INVALID_CODE(10000,"验证码无效"), USERNAME_NOT_EXISTS(10001,"用户名不存在"), USER_CREDIT_NOT_ENOUTH(10002,"用户积分不足"); ; private int code ; private String msg ; public int getCode() { return code; } public String getMsg() { return msg; } AppExceptionCodeMsg(int code, String msg){ this.code = code; this.msg = msg; } } ``` ## 全局异常拦截器Handler 这个拦截器的作用就是在抛出异常之前进行拦截,先判断是不是要抛出你自定义的异常,如果不是则放行。 ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(value = {Exception.class}) @ResponseBody public Resp exceptionHandler(Exception e){ //这里先判断拦截到的Exception是不是我们自定义的异常类型 if(e instanceof AppException){ AppException appException = (AppException)e; return Resp.error(appException.getCode(),appException.getMsg()); } //如果拦截的异常不是我们自定义的异常(例如:数据库主键冲突) return Resp.error(500,"服务器端异常"); } } ``` ## 响应类模板Resp 其实这个响应类模板网上到处都是,自己也可以随意找到,以下是我的模板: ```java public class Resp { //服务端返回的错误码 private int code = 200; //服务端返回的错误信息 private String msg = "success"; //我们服务端返回的数据 private T data; private Resp(int code,String msg,T data){ this.code = code; this.msg = msg; this.data = data; } public static Resp success(T data){ Resp resp = new Resp(200, "success", data); return resp; } public static Resp success(String msg,T data){ Resp resp = new Resp(200,msg, data); return resp; } public static Resp error(AppExceptionCodeMsg appExceptionCodeMsg){ Resp resp = new Resp(appExceptionCodeMsg.getCode(), appExceptionCodeMsg.getMsg(), null); return resp; } public static Resp error(int code,String msg){ Resp resp = new Resp(code,msg, null); return resp; } public int getCode() { return code; } public String getMsg() { return msg; } public T getData() { return data; } } ``` ## 案例展示 || Demo 接下来我将用一个SpringBoot项目综合上述异常类与响应类综合展示具体情况,看官们也可以自行下载demo直接在自己的电脑上跑起来学习。 ### 项目结构 ```xml │ pom.xml ├─src │ ├─main │ │ ├─java │ │ │ └─com │ │ │ └─linghu │ │ │ └─demo │ │ │ │ DemoApplication.java │ │ │ │ │ │ │ ├─controller │ │ │ │ DemoController.java │ │ │ │ │ │ │ ├─exception │ │ │ │ AppException.java │ │ │ │ AppExceptionCodeMsg.java │ │ │ │ GlobalExceptionHandler.java │ │ │ │ │ │ │ └─resp │ │ │ Resp.java │ │ │ │ │ └─resources │ │ application.yml │ │ │ └─test │ └─java ``` ### pom依赖 ```xml 4.0.0 org.example exceptiondemo 1.0-SNAPSHOT 8 8 UTF-8 2.3.7.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import ``` ### DemoController web层api代码设计如下: ```java @RestController public class DemoController { @GetMapping("demo") public Resp demo1(String name){ if("ok".equals(name)){ return Resp.success("succ"); } if("err".equals(name)){ //抛业务相关的异常 throw new AppException(AppExceptionCodeMsg.USERNAME_NOT_EXISTS); } if("errcode".equals(name)){ throw new AppException(AppExceptionCodeMsg.INVALID_CODE); } if("0".equals(name)){ int i=1/0; } //检查用户积分是否足够,如果不够,就抛出异常 if("notenough".equals(name)){ throw new AppException(AppExceptionCodeMsg.USER_CREDIT_NOT_ENOUTH); } return Resp.success("default"); } @GetMapping("list") public Resp list(){ List list = Arrays.asList("zhangsan","lisi","wangwu"); return Resp.success(list); } } ``` ### 实际执行结果 ![输入图片说明](target/classes/image.png) 大家可以自行下载代码跑一跑学习一下。 ## Demo案例Git地址 | Gitee 该教程其实很简单,欢迎大家下载学习! 代码链接如下: