Spring 异常处理
目录
SpringBoot 中有一个 ControllerAdvice 的注解,使用该注解表示开启了全局异常的捕获,我们只需在自定义一个方法使用 ExceptionHandler 注解然后定义捕获异常的类型即可对这些捕获的异常进行统一的处理。
【示例】
- 封装一个返回体
这里,我们需要先定义一个全局异常类 BaseException
,然后再定义一个通用返回体:
@Data public class GenericResponseBody { private String msg; private String code; public ErrorResponse(String code, String msg) { this.code = code; this.msg = msg; } public static GenericResponseBody fail(Exception e) { this.code = 10001; this.msg = e.msg(); } public static GenericResponseBody fail(BaseException e) { this.code = e.getCode(); this.msg = e.msg(); } }
- 定义一个全局异常处理器
@ControllerAdvice(assignableTypes = {ExceptionController.class}) @ResponseBody public class GlobalExceptionHandler { @ExceptionHandler(value = Exception.class) public ResponseEntity<GenericResponseBody> baseExceptionHandler(BaseException e) { return ResponseEntity.status(200).body(GenericResponseBody.fail(e)); } @ExceptionHandler(value = Exception.class) public ResponseEntity<GenericResponseBody> exceptionHandler(Exception e) { return ResponseEntity.status(400).body(GenericResponseBody.fail(e)); } }
参考:
本文作者:LARRY1024
本文链接:https://www.cnblogs.com/larry1024/p/17775259.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步