打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Spring Boot统一异常处理

Spring boot 通过AOP思想,使用注解@RestControllerAdvice将异常统一到一个地方进行处理,这样可以避免代码中到处捕获和处理异常,让代码保持干净整洁。


简单对象的创建

首先创建一个枚举类型,用来保存各种返回状态

public enum ResultCode {    SUCCESS(200, "成功"),    PARAM_INVALID(401, "参数无效"),    TASK_NULL(404, "任务不存在"),   ...    private int code;    private String msg;    ResultCode(int code, String msg) {        this.code = code;        this.msg = msg;    }    public int getCode() {        return code;    }    public String getMsg() {        return msg;    }}

然后再有一个统一的controller返回对象类:

public class ResultJson<T> implements Serializable{    private static final long serialVersionUID = 783015033603078674L;    private int code;    private String msg;    private T data;    public ResultJson (ResultCode resultCode,T data) {        setResultCode(resultCode);        this.data = data;    }    public static ResultJson success() {        ResultJson resultJson = new ResultJson();        resultJson.setResultCode(ResultCode.SUCCESS);        return resultJson;    }    public static <T> ResultJson success(T data){        return new ResultJson(ResultCode.SUCCESS, data);    }    public static ResultJson failure(ResultCode resultCode){        ResultJson resultJson = new ResultJson();        resultJson.setResultCode(resultCode);        return resultJson;    }    public void setResultCode(ResultCode resultCode) {        this.code = resultCode.getCode();        this.msg = resultCode.getMsg();    }...省略构造方法和getter和setter方法;}

自定义异常类:

public class CustomException extends RuntimeException {    private static final long serialVersionUID = 2984474148327146104L;    private ResultCode resultCode;    public CustomException(ResultCode resultCode) {        this.resultCode = resultCode;    }    ...省略getter和setter方法;}

然后就是创建一个统一异常处理的类了

@RestControllerAdvicepublic class DefaultExceptionHandler {    private Logger logger = LoggerFactory.getLogger(DefaultExceptionHandler.class);    /**     * 处理所有自定义异常     * @param e     * @return     */    @ExceptionHandler(CustomException.class)    public ResultJson handleCustomException(CustomException e){        return ResultJson.failure(e.getResultCode());    }  ...这里可以增加其他想处理的异常    /**     * 处理所有异常     * @param e     * @return     */    @ExceptionHandler(Exception.class)    public ResultJson handleException(Exception e){        logger.error(e.getMessage());        return ResultJson.failure(ResultCode.SERVER_ERROR);    }}

该类会拦截controller转发的请求过程中产生的异常,只要在异常处理类中定义的异常都可以被捕获处理,并返回给controller调用者。
业务方法中就可以不用去处理异常了。异常都集中到一处处理,修改也方便,而且所有定义的异常都能按照格式返回到前台。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
SpringBoot-22-RESTful统一规范响应数据格式
Spring Boot 引入自定义yml
Sping boot 静态资源文件的路径配置
Spring Boot使用Spring Security实现权限控制
Spring Boot 全局异常处理整理
在Spring Boot中使用Spring Security实现权限控制
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服