全局异常处理
传送门:
spring-boot-route(四)全局异常处理
在开发中,我们经常会使用try/catch块
来捕获异常进行处理,如果有些代码中忘记捕获异常或者不可见的一些异常出现,就会响应给前端一些不友好的提示,这时候我们可以使用全局异常处理。这样就不用在代码中写那些烦人的try/catch块了
,代码的可读性也会提高。
SpringBoot提供的的注解@ControllerAdvice
配合 @ExceptionHandler
实现全局异常处理
定义响应状态码及信息的枚举类
public enum ErrorCodeEnum { SUCCESS(0, "请求成功"), ERROR(500, "未知异常"), ERROR_EMPTY_RESULT(1001, "查询结果为空"), ERROR_INCOMPLETE_RESULT(1002, "请求参数不全"); private int code; private String message; ErrorCodeEnum(int code, String message) { this.code = code; this.message = message; } public int getCode() { return code; } public String getMessage() { return message; } }
自定义异常类
public class CutsomException extends Exception { private int code; private String message; public CutsomException(ErrorCodeEnum errorCodeEnum) { this.code = errorCodeEnum.getCode(); this.message = errorCodeEnum.getMessage(); } }
定义全局异常处理类
由于这里我想要响应的结果为实体类对象,因此我直接用@RestControllerAdvice
来代替了@ControllerAdvice
,这两个注解的差别跟@Controller
和@RestController
一样,rest的响应体为json格式的数据。
@RestControllerAdvice public class GlobalExceptionHandle { /** * 处理自定义异常 * * @param e * @return */ @ExceptionHandler(CustomException.class) public RestResult customExceptionHandler(CustomException e) { // 日志打印等处理 System.out.println("进入全局异常-自定义异常处理"); RestResult restResult = new RestResult(); restResult.setCode(e.getCode()); restResult.setErrMsg(e.getErrMsg()); return restResult; } /** * 其他异常处理 * * @param e * @return */ @ExceptionHandler public RestResult otherExceptionHandler(Exception e) { return RestResult.failResult(e.getMessage()); } }
测试自定义异常
@RestController @RequestMapping("/curl-test") public class DemoController { @GetMapping("/test-exception") public RestResult testCustomException(String flag) throws Exception { if ("1".equals(flag)) { throw new CustomException(ErrorCodeEnum.ERROR_INCOMPLETE_RESULT); } if ("2".equals(flag)) { throw new Exception("其他异常"); } return RestResult.successResult(); } }
本文来自博客园,作者:Lz_蚂蚱,转载请注明原文链接:https://www.cnblogs.com/leizia/p/17156345.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步