Spring Boot學習——統一異常處理
阿新 • • 發佈:2017-07-30
return 方法 ssa static framework 處理異常 tor ebo except
本隨筆記錄使用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學習——統一異常處理