首页 > 作文

SpringBoot中如何进行统一异常处理

更新时间:2023-04-04 21:31:25 阅读: 评论:0

目录
1、处理前2、进行系统异常全局处理3、进行自定义异常处理总结

如何在springboot项目里进行统一异常处理 需要了解的知识

@controlleradvice的作用

1、处理前

异常代码

/**     * 根据id获取医院设置     *     * @param id 查看的id编号     * @return     */@apioperation(value = "根据id获取医院设置")@getmapping("/findhospbyid/{id}")public result findhospbyid(@pathvariable long id) {    // 模拟异常(因为除数不能为0)    int a = 1 / 0;    hospitalt hospitalt = hospitaltrvice.getbyid(id);    return result.ok(hospitalt);}

swagger2输出结果

2、进行系统异常全局处理

添加全局异常处理类

代码

package com.fafa.yygh.common.exception;import com.fafa.yygh.common.result.result;import org.springframework.web.bind.annotation.controlleradvice;import org.springframework.web.bind.annotation.exceptionhandler;import org.springframework.web.bind.annotation.responbody;/** * 全局异常处理 * * @author sire * @version 1.0 * @date 2022-02-02 21:01 */@controlleradvicepublic class globalexceptionhandler {    /**     * 系统异常处理     *     * @param e     * @return     */    @exceptionhandle初学者怎样化妆r(exception.class)    @responbody    public result error(exception e) {        e.printstacktrace();        return result.fail();    }}

swagger2结果

3、进行自定义异常处理

开发时,往往需要我们去定义处理一些异常(这里还是那上面的那个异常来做测试)

创建自定义异常处理类

package com.fafa.yygh.common.exception;import com.fafa.yygh.common.result.resultcodeenum;import io.swagger.annotations.apimodel;import io.swagger.annotations.apimodelproperty;import lombok.data;/** * 自定义全局异常类 * * @author qy */@data@apimodel(value = "自定义全局异常类")public class yyghexception extends runtimeexception {    @apimodelproperty(value = "异常状态码")    private integer code;    /**     * 通过状态码和错误消息创建异常对象     *     * @param message     * @param code     */    public yyghexception(string message, integer code) {        super(message);        this.code = code;    }    /**     * 接收枚举类型对象     *     * @param resultcodeenum     */    public yyghexception(resultcodeenum resultcodeenum) {        super(resultcodeenum.getmessage());        this.code = resultcodeenum.getcode();    史说汉字}    @override    public string tostring() {        return "yyghex小说题目的作用ception{" +            "code=" + code +            ", message=" + this.getmessage() +            '}';    }}

将其添加到globalexceptionhandler

/**     * 自定义异常处理     *     * @param e     * @return     */@exceptionhandler(yyghexception.class)@responbodypublic result diver反腐倡廉学习心得ror(yyghexception e) {    return result.buil拜托老师多费心的句子d(e.getcode(), e.getmessage());}

需要手动 try catch 一下

效果

swagger和系统异常处理一样

不过后台输出不一样

总结

到此这篇关于springboot中如何进行统一异常处理的文章就介绍到这了,更多相关springboot异常处理内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

本文发布于:2023-04-04 21:31:24,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/zuowen/c2b3c28fd1872065aa863251cac75a16.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

本文word下载地址:SpringBoot中如何进行统一异常处理.doc

本文 PDF 下载地址:SpringBoot中如何进行统一异常处理.pdf

下一篇:返回列表
标签:异常   自定义   全局   系统
相关文章
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图