序言:不少时候都要写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