序言:不少時候都要寫try catch,因此爲了減小代碼把異常處理單獨拿出來,作一個全局處理,通常公司都是自定義異常爲主,今天寫一個默認異常和自定義異常的配置,很簡單,五分鐘就能掌握,並且代碼全面,屬於企業用法。spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
server.port=8082
@Data @AllArgsConstructor public class Result { private boolean success; private String code; private String message; private Object data; public Result() { this.success = true; this.code = "200"; } }
@Data @NoArgsConstructor @AllArgsConstructor public class MyException extends RuntimeException { /** * 異常狀態碼 */ private String code; /** * 異常信息 */ private String message; /** * 發生的方法 */ private String method; /** * 描述 */ private String desc; }
@ControllerAdvice public class MyControllerAdvice { /** * 全局異常處理 */ @ResponseBody @ExceptionHandler(value = Exception.class) public Result exceptionHandler(Exception e){ Result result = new Result(); result.setCode("201"); result.setSuccess(false); result.setMessage(e.getMessage()); //異常業務邏輯處理(日誌記錄或者其餘存儲) return result; } /** * 自定義異常 */ @ResponseBody @ExceptionHandler(value = MyException.class) public Result exceptionHandler(MyException e) { Result result = new Result(); result.setCode(e.getCode()); result.setMessage(e.getMessage()); result.setSuccess(false); result.setData(e.getDesc()); return result; } }
@Controller public class FirstController { @RequestMapping(value = "/test",method = RequestMethod.GET) @ResponseBody public Result test1() throws Exception { throw new Exception("dnwbid"); } @RequestMapping(value = "/test2",method = RequestMethod.GET) @ResponseBody public Result test2() { throw new MyException("201","測試異常保持","testOne","desc"); } }
http://localhost:8082/test1app
http://localhost:8082/test2spring-boot