SpringBoot统一异常处理
在系统中异常处理是很重要的一块,今天介绍统一处理异常的一种方法,记录以便学习参考。
本例中模拟:从数据库中根据ID查询学生信息,要求学生的年龄在14——20岁之间。小于14岁,提示“你可能在上初中”;大于20岁,提示“你可能在上大学”。
用异常的方式来处理.
详见代码:
第一步,创建枚举类ResultEnum,用来管理异常信息

package *;//自己定义 public enum ResultEnum { UNKONW_ERROR(-1, "未知错误"), SUCCESS(0, "成功"), PRIMARY_SCHOOL(100, "年龄小于14岁,可能正在上中学"), UNIVERSITY(101, "年龄大于20岁,可能正在上大学"); private Integer code; private String msg; ResultEnum( Integer code, String msg){ this.code = code; this.msg = msg; } public Integer getCode(){ return this.code; } public String getMsg(){ return this.msg; } }
第二步,创建自己的异常类StudentException,代码如下:

package *;//自己定义 import *.ResultEnum; //自己定义路径 public class StudentException extends RuntimeException { private Integer code; public StudentException(ResultEnum resultEnum){ super(resultEnum.getMsg()); this.code = resultEnum.getCode(); } public void setCode(Integer code) { this.code = code; } public Integer getCode() { return code; } }
第三步,创建返回报文实体类Result.java

@Data public class Result { private Integer code; private String msg; private Object date; }
第四步,创建请求返回工具类ResultUtil.java

package *;//自己定义 import *.Result;//自己定义的路径 /** * HTTP请求返回处理工具类 */ public class ResultUtil { public static Result success(){ return success(null); } public static Result success(Object object){ Result result = new Result(); result.setCode(0); result.setMsg("成功"); result.setDate(object); return result; } public static Result error(Integer code, String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } }
第五步,创建统一处理异常的类ExceptionHandle.java,代码如下:

package *; //自己定义 import *.StudentException; //自己定义路径 import *.Result; //自己定义路径 import *.ResultUtil; //自己定义路径 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class ExceptionHandle { private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class) @ResponseBody public Result handler( Exception e){ if( e instanceof StudentException){ StudentException studentException = (StudentException) e; return ResultUtil.error( studentException.getCode(), studentException.getMessage()); }else { logger.info("[系统异常] {}",e); return ResultUtil.error( -1, "未知错误"); } } }
第六步,在service中编写业务逻辑代码:

package com.example.demo.Service; import com.example.demo.Exception.StudentException; import com.example.demo.Utils.ResultEnum; import com.example.demo.Vo.Student; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created with IntelliJ IDEA. * Author: zhangz * Date: 2019/8/20 * Time: 15:42 */ @Service public class StudentService { //@Autowired //private StudentRepository studentRepository; /** * 根据ID查询符合条件的学生 * @param id * @throws Exception */ public Student getStudentById(Integer id) throws Exception{ //Student student = studentRepository.findOne(id); //Integer age = student.getAge(); Integer age =12; if(age < 14){ throw new StudentException(ResultEnum.PRIMARY_SCHOOL); }else if(age > 20){ throw new StudentException(ResultEnum.UNIVERSITY); } Student student =new Student(); student.setAge(age); //进行下面逻辑操作 return student; } }
第七步,在controller中调用service方法,代码如下:

package com.example.demo.Controller; import com.example.demo.Service.StudentService; import com.example.demo.Utils.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** * Created with IntelliJ IDEA. * Author: zhangz * Date: 2019/8/20 * Time: 15:43 */ @RestController public class StudentController { @Autowired private StudentService studentService; /** * 根据ID查询学生 */ @GetMapping(value = "/student/getage/{id}") public Result getStudentById(@PathVariable("id") Integer id) throws Exception{ return ResultUtil.success(studentService.getStudentById(id)); } }
最后,访问http://127.0.0.1:8080/student/getage/1 ,查看结果。
表明异常梳理成功。
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】Flutter适配HarmonyOS 5知识地图,实战解析+高频避坑指南
【推荐】开源 Linux 服务器运维管理面板 1Panel V2 版本正式发布
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 大数据高并发核心场景实战,数据持久化之冷热分离
· 运维排查 | SaltStack 远程命令执行中文乱码问题
· Java线程池详解:高效并发编程的核心利器
· 从“看懂世界”到“改造世界”:AI发展的四个阶段你了解了吗?
· 协程本质是函数加状态机——零基础深入浅出 C++20 协程
· 基于.net6的一款开源的低代码、权限、工作流、动态接口平台
· 一个自认为理想主义者的程序员,写了5年公众号、博客的初衷
· Claude Code 初体验 - Windows
· LinqPad:C#代码测试学习一品神器
· .NET 8 gRPC 实现高效100G大文件断点续传工具