千家信息网

springboot如何自定义异常并捕获异常返给前端

发表于:2026-11-02 作者:千家信息网编辑
千家信息网最后更新 2026年11月02日,小编给大家分享一下springboot如何自定义异常并捕获异常返给前端,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!背景在
千家信息网最后更新 2026年11月02日springboot如何自定义异常并捕获异常返给前端

小编给大家分享一下springboot如何自定义异常并捕获异常返给前端,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

背景

在开发中,如果用try catch的方式,每个方法都需要单独实现,为了方便分类异常,返回给前端,采用了@ControllerAdvice注解和继承了RuntimeException的方式来实现。

实现内容

捕获了三类异常
1.业务异常

BusinessException

2.系统异常

SystemException

3.其他异常

利用@ExceptionHandler(RuntimeException.class)去捕获

ExceptionAdvice类捕获以上三类异常,并返回自定义类型格式数据

实现代码

业务异常BusinessException类实现方式,继承RuntimeException

public class BusinessException extends  RuntimeException {        /**         * 错误编码         */        private String code;         public BusinessException() {                super();        }         public BusinessException(String message) {                super(message);        }         public BusinessException(String code, String message) {                super(message);                this.code = code;        }         public BusinessException(Throwable cause) {                super(cause);        }         public BusinessException(String message, Throwable cause) {                super(message, cause);        }         public BusinessException(String message, Throwable cause,                                                         boolean enableSuppression, boolean writableStackTrace) {                super(message, cause, enableSuppression, writableStackTrace);        }         public String getCode() {                return code;        }         public void setCode(String code) {                this.code = code;        }         @Override        public String getMessage() {                return super.getMessage();        }         @Override        public String toString() {                return this.code + ":" + this.getMessage();        }}

系统异常SystemException类实现方式,继承RuntimeException,同业务异常类的实现方式一样

public class SystemException extends  RuntimeException {        /**         * 错误编码         */        private String code;         public SystemException() {                super();        }         public SystemException(String message) {                super(message);        }         public SystemException(String code, String message) {                super(message);                this.code = code;        }         public SystemException(Throwable cause) {                super(cause);        }         public SystemException(String message, Throwable cause) {                super(message, cause);        }         public SystemException(String message, Throwable cause,                           boolean enableSuppression, boolean writableStackTrace) {                super(message, cause, enableSuppression, writableStackTrace);        }         public String getCode() {                return code;        }         public void setCode(String code) {                this.code = code;        }         @Override        public String getMessage() {                return super.getMessage();        }         @Override        public String toString() {                return this.code + ":" + this.getMessage();        }}

ExceptionAdvice类,采用增强Controller注解 @ControllerAdvice的方式来实现

1.方法名称和返回类型都可以根据自己需要定义;

2.采用注解@ExceptionHandler,就是捕获的异常类型,我们只需要把需要捕获异常类型写进来就好

ExceptionAdvice 具体代码实现如下:

import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvicepublic class ExceptionAdvice {    public static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);     @ResponseBody    @ExceptionHandler(SystemException.class)    public Result handleException(Exception e) {        logger.error("系统异常信息:", e);        Result result = new Result();        if (e instanceof BusinessException) {            e = (BusinessException) e;            result.setCode(((BusinessException) e).getCode());        }        result.setFailed(e.getMessage());        return result;    }     @ExceptionHandler(RuntimeException.class)    @ResponseBody    public Result handleException(RuntimeException e) {        logger.error("异常信息:", e.getMessage());        Result result = new Result();        result.setStatus(500);        result.setMessage(e.getMessage());        return result;    }     @ExceptionHandler(BusinessException.class)    @ResponseBody    public AjaxJson doBusinessException(Exception e) {        AjaxJson ajaxJson = new AjaxJson();        logger.error("业务异常消息:", e.getMessage());        ajaxJson.setRet(-1);        ajaxJson.setMsg(e.getMessage());        return ajaxJson;    } }

测试代码

1.我们捕获一个业务异常BusinessException,输出aaa

2.捕获系统异常

throw new SystemException("aaaa");

3.其他的try catch的异常,这个就可以捕获了

以上是"springboot如何自定义异常并捕获异常返给前端"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

方式 业务 类型 系统 前端 代码 内容 注解 篇文章 信息 方法 编码 错误 不怎么 名称 大部分 就是 数据 更多 格式 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 亿人帮互联网科技有限公司 科技互联网企业 厦门中拓互联网络科技有限公司 北京互联网科技公司 凡科互联网科技 无线互联网科技 时间互联网络科技 新浪科技互联网 赫美联合互联网科技 深圳期待互联网科技 互联网高科技股票 佰商互联网科技有限公司 汉立互联网科技有限公司联系电话 中国科技互联网公司收入 工业互联网等科技实现智能化赋能 上海科技产业互联网平台 北京天晋互联网科技有限公司 互联网科技创新创业项目 北京品多多互联网科技有限公司 广州全民伙伴互联网科技有限公司 云南咖啡 互联网科技有限公司经营范围 壹账通互联网科技 苏州互联网科技贷款公司 苏州大垚互联网科技 佳云科技和互联网广告 企晟互联网信息科技有限公司 互联网企业科技类企业如何做账 2021世界互联网领先科技成果发布 广州全民伙伴互联网科技有限公司
0