Spring Boot学习——统一异常处理
Posted aston
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot学习——统一异常处理相关的知识,希望对你有一定的参考价值。
本随笔记录使用Spring Boot统一处理异常。
本文实例是从数据库中根据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
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; } }
第四步,创建请求返回工具类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 *; //自己定义 import *.ResultEnum; //自己定义的路径 import *.StudentException; //自己定义的路径 import *.StudentRepository; //自己定义的路径 import *.Student; //自己定义的路径 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.transaction.Transactional; @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(); if(age < 14){ throw new StudentException(ResultEnum.PRIMARY_SCHOOL); }else if(age > 20){ throw new StudentException(ResultEnum.UNIVERSITY); } //进行下面逻辑操作 return student; } }
第七步,在controller中调用service方法,代码如下:
package *; //自己定义路径 import *.Result; //自己定义路径 import *.StudentService; //自己定义路径 import *.ResultUtil; //自己定义路径 import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.List; @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)); } }
最后,使用postman访问http://127.0.0.1:8080/student/getage/1 ,查看结果。
以上是关于Spring Boot学习——统一异常处理的主要内容,如果未能解决你的问题,请参考以下文章