当前位置: 代码网 > it编程>编程语言>Java > springboot实现全局异常处理的方法(住家饭系统)

springboot实现全局异常处理的方法(住家饭系统)

2025年05月06日 Java 我要评论
在实际项目开发中,定义全局异常处理至关重要通过全局异常处理器(使@controlleradvice和@exceptionhandler注解),可以集中捕获和处理各种异常,避免在每个控制器方法中重复编写

在实际项目开发中,定义全局异常处理至关重要通过全局异常处理器(使@controlleradvice@exceptionhandler注解),可以集中捕获和处理各种异常,避免在每个控制器方法中重复编写异常处理代码。

住家饭系统将异常类型分为客户端异常(clientexception),系统异常(serviceexception),远程调用异常(remoteexception)。类结构图如下:

我们需先定义一个抽象异常类 abstractexception ,该抽象类继承自 runtimeexception 类,通过该类约束异常类行为。

/**
 * 抽象项目中的三类异常,客户端异常、服务端异常和远程服务调用异常
 */
@data
public abstract class abstractexception extends runtimeexception{
    public final string errorcode;
    public final string errormsg;
    public abstractexception(string errormsg, throwable throwable, ierrorcode errorcode) {
        super(errormsg, throwable);
        this.errorcode = errorcode.code();
        this.errormsg = optional.ofnullable(stringutils.haslength(errormsg) ? errormsg : null).orelse(errorcode.msg());
    }
}

接着在分别定义客户端异常、服务端异常和远程调用异常类。

public class clientexception extends abstractexception{
    public clientexception (ierrorcode errorcode) {
        super(null, null, errorcode);
    }
    public clientexception(ierrorcode errorcode, string errormsg) {
        super(errormsg, null, errorcode);
    }
    public clientexception(string message, throwable throwable, ierrorcode errorcode) {
        super(message, throwable, errorcode);
    }
    @override
    public string tostring() {
        return "clientexception{" +
                "code='" + errorcode + "'," +
                "message='" + errormsg + "'" +
                '}';
    }
}
public class serviceexception extends abstractexception{
    public serviceexception(string message) {
        this(message, null, baseerrorcode.service_error);
    }
    public serviceexception(ierrorcode errorcode) {
        this(null, errorcode);
    }
    public serviceexception(string message, ierrorcode errorcode) {
        this(message, null, errorcode);
    }
    public serviceexception(string message, throwable throwable, ierrorcode errorcode) {
        super(optional.ofnullable(message).orelse(errorcode.msg()), throwable, errorcode);
    }
    @override
    public string tostring() {
        return "serviceexception{" +
                "code='" + errorcode + "'," +
                "message='" + errormsg + "'" +
                '}';
    }
}
public class remoteexception extends abstractexception{
    public remoteexception(string errormsg, throwable throwable, ierrorcode errorcode) {
        super(errormsg, throwable, errorcode);
    }
    @override
    public string tostring() {
        return "remoteexception{" +
                "code='" + errorcode + "'," +
                "message='" + errormsg + "'" +
                '}';
    }
}

这样,我们就完成了对三大基本异常类的定义。接下来我们需要通过springboot提供的@controlleradvice@exceptionhandler注解来实现全局异常拦截并处理。我们需定义一个globalexceptionhandler类,在该类中分别对参数验证异常、应用内抛出的异常和最顶级的throwable异常进行处理。

component("globalexceptionhandlerbyadmin")
@slf4j
@restcontrolleradvice
public class globalexceptionhandler {
    /**
     * 拦截参数验证异常
     */
    @sneakythrows
    @exceptionhandler(value = methodargumentnotvalidexception.class)
    public result validexceptionhandler(httpservletrequest request, methodargumentnotvalidexception ex) {
        bindingresult bindingresult = ex.getbindingresult();
        fielderror firstfielderror = collectionutil.getfirst(bindingresult.getfielderrors());
        string exceptionstr = optional.ofnullable(firstfielderror)
                .map(fielderror::getdefaultmessage)
                .orelse(strutil.empty);
        log.error("[{}] {} [ex] {}", request.getmethod(), geturl(request), exceptionstr);
        return results.failure(baseerrorcode.client_error.code(), exceptionstr);
    }
    /**
     * 拦截应用内抛出的异常
     */
    @exceptionhandler(value = {abstractexception.class})
    public result abstractexception(httpservletrequest request, abstractexception ex) {
        if (ex.getcause() != null) {
            log.error("[{}] {} [ex] {}", request.getmethod(), request.getrequesturl().tostring(), ex.tostring(), ex.getcause());
            return results.failure(ex);
        }
        log.error("[{}] {} [ex] {}", request.getmethod(), request.getrequesturl().tostring(), ex.tostring());
        return results.failure(ex);
    }
    /**
     * 拦截未捕获异常
     */
    @exceptionhandler(value = throwable.class)
    public result defaulterrorhandler(httpservletrequest request, throwable throwable) {
        log.error("[{}] {} ", request.getmethod(), geturl(request), throwable);
        if (objects.equals(throwable.getclass().getsuperclass().getsimplename(), abstractexception.class.getsimplename())) {
            string errorcode = reflectutil.getfieldvalue(throwable, "errorcode").tostring();
            string errormessage = reflectutil.getfieldvalue(throwable, "errormessage").tostring();
            return results.failure(errorcode, errormessage);
        }
        return results.failure();
    }
    private string geturl(httpservletrequest request) {
        if (stringutils.isempty(request.getquerystring())) {
            return request.getrequesturl().tostring();
        }
        return request.getrequesturl().tostring() + "?" + request.getquerystring();
    }
}

今后,我们在项目里抛出的所有异常,都可以被 globalexceptionhandler 类捕获并进行相应的处理。

    public void register(userregisterreqdto requestparam) {
        if(objectutils.isempty(requestparam)) throw new clientexception(client_error);
        if (hasusername(requestparam.getusername())) {
            throw new serviceexception(user_name_exist);
        }
        try {
            int inserted = basemapper.insert(beanutil.tobean(requestparam, userdao.class));
            if (inserted <= 0) {
                throw new clientexception(user_save_error);
            }
        }  catch (duplicatekeyexception ex) {
            throw new serviceexception(user_exist);
        }
    }

到此这篇关于springboot实现全局异常处理的文章就介绍到这了,更多相关springboot全局异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com