springboot统一处理异常
增加业务异常处理类:
package com.example.demo.config; import lombok.Data; @Data public class BizException extends RuntimeException{ protected Integer errorCode; protected String errorMsg; public BizException(){ } public BizException(Integer errorCode, String errorMsg) { this.errorCode = errorCode; this.errorMsg = errorMsg; } }
设置异常handler:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | package com.example.demo.config; import lombok.Data; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @Data class ErrorObj<T>{ //是否成功 private Boolean success; //状态码 private Integer code; //提示信息 private String msg; //数据 private T data; } @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler (value =Exception. class ) @ResponseBody public ErrorObj exceptionHandler(Exception e){ System.out.println( "发生了一个运行时异常" +e); ErrorObj errObj = new ErrorObj(); errObj.setSuccess( false ); errObj.setCode( 1 ); errObj.setMsg(e.getMessage()); errObj.setData( "" ); return errObj; } @ExceptionHandler (value =BizException. class ) @ResponseBody public ErrorObj bizexceptionHandler(BizException e){ System.out.println( "发生了一个业务异常" +e); ErrorObj errObj = new ErrorObj(); errObj.setSuccess( false ); errObj.setCode(e.getErrorCode()); errObj.setMsg(e.getErrorMsg()); errObj.setData( "" ); return errObj; } } |
测试:
@RequestMapping("/hello") public void hello() throws BizException { throw new BizException(1, "我抛出了一个错误"); } @RequestMapping("/zeroException") public Integer zeroException(){ return 100/0; }
执行结果:
{"success":false,"code":1,"msg":"/ by zero","data":""}
{"success":false,"code":1,"msg":"我抛出了一个错误","data":""}
命令行输出:
本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/17062755.html

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步