当前位置: 代码网 > it编程>编程语言>Java > SpringMVC实现全局异常处理器的经典案例

SpringMVC实现全局异常处理器的经典案例

2025年03月26日 Java 我要评论
通过 @controlleradvice 注解,我们可以在一个地方对所有 @controller 注解的控制器进行管理。注解了 @controlleradvice 的类的方法可以使用 @excepti

通过 @controlleradvice 注解,我们可以在一个地方对所有 @controller 注解的控制器进行管理。
注解了 @controlleradvice 的类的方法可以使用 @exceptionhandler、 @initbinder、 @modelattribute 注解到方法上,这对所有注解了 @requestmapping 的控制器内的方法都有效。

@exceptionhandler:用于捕获所有控制器里面的异常,并进行处理。@initbinder:用来设置 webdatabinder,webdatabinder 用来自动绑定前台请求参数到 model 中。@modelattribute:@modelattribute 本来的作用是绑定键值对到 model
里,此处是让全局的@requestmapping 都能获得在此处设置的键值对。

本文使用 @controlleradvice + @exceptionhandler 进行全局的 controller 层异常处理。只要设计得当,就再也不用在 controller 层进行 try-catch 了!

一、经典案例

需求:希望通过全局统一的异常处理将自定义错误码以json的形式发送给前端。
1、统一返回结果类 apiresult
首先,定义一个统一结果返回类,最终需要将这个结果类的内容返回给前端。

package com.tao.smp.exception;
/**
 * api统一的返回结果类
 */
public class apiresult {
    /**
     * 结果码
     */
    private string code;
    /**
     * 结果码描述
     */
    private string msg;
    public apiresult() {
    }
    public apiresult(resultcode resultcode) {
        this.code = resultcode.getcode();
        this.msg = resultcode.getmsg();
    }
    /**
     * 生成一个apiresult对象, 并返回
     *
     * @param resultcode
     * @return
     */
    public static apiresult of(resultcode resultcode) {
        return new apiresult(resultcode);
    }
    public string getcode() {
        return code;
    }
    public void setcode(string code) {
        this.code = code;
    }
    public string getmsg() {
        return msg;
    }
    public void setmsg(string msg) {
        this.msg = msg;
    }
    @override
    public string tostring() {
        return "apiresult{" +
                "code='" + code + '\'' +
                ", msg='" + msg + '\'' +
                '}';
    }
}

2、错误码枚举类 resultcode
有了 apiresult ,接下来需要定义一个枚举类, 来包含所有自定义的结果码。

package com.tao.smp.exception;
/**
 * 错误码
 */
public enum resultcode {
    /**
     * 成功
     */
    success("0", "success"),
    /**
     * 未知错误
     */
    unknown_error("0x10001", "unkonwn error"),
    /**
     * 用户名错误或不存在
     */
    username_error("0x10002", "username error or does not exist"),
    /**
     * 密码错误
     */
    password_error("0x10003", "password error"),
    /**
     * 用户名不能为空
     */
    username_empty("0x10004", "username can not be empty");
    /**
     * 结果码
     */
    private string code;
    /**
     * 结果码描述
     */
    private string msg;
    resultcode(string code, string msg) {
        this.code = code;
        this.msg = msg;
    }
    public string getcode() {
        return code;
    }
    public string getmsg() {
        return msg;
    }
}

3、自定义业务异常类 businessruntimeexception
接下来需要定义我们自己的业务异常类,以后和业务相关的异常通通抛出这个异常类,我们将错误码枚举变量的值存于其中。

package com.tao.smp.exception;
/**
 * 自定义业务异常
 */
public class businessruntimeexception extends runtimeexception {
    /**
     * 结果码
     */
    private string code;
    /**
     * 结果码描述
     */
    private string msg;
    /**
     * 结果码枚举
     */
    private resultcode resultcode;
    public businessruntimeexception(resultcode resultcode) {
        super(resultcode.getmsg());
        this.code = resultcode.getcode();
        this.msg = resultcode.getmsg();
        this.resultcode = resultcode;
    }
    public string getcode() {
        return code;
    }
    public void setcode(string code) {
        this.code = code;
    }
    public string getmsg() {
        return msg;
    }
    public void setmsg(string msg) {
        this.msg = msg;
    }
    public resultcode getresultcode() {
        return resultcode;
    }
    public void setresultcode(resultcode resultcode) {
        this.resultcode = resultcode;
    }
}

4、全局异常处理类 globalexceptionresolver

最后便是定义全局异常处理类。

  • 通过 @controlleradvice 指定该类为 controller 增强类。
  • 通过 @exceptionhandler 自定捕获的异常类型。
  • 通过 @responsebody 返回 json 到前端。

注意一点:被@controlleradvice注解的全局异常处理类也是一个 controller ,我们需要配置扫描路径,确保能够扫描到这个controller。

package com.tao.smp.exception;
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;
/**
 * 全局controller层异常处理类
 */
@controlleradvice
public class globalexceptionresolver {
    private static final logger log = loggerfactory.getlogger(globalexceptionresolver.class);
    /**
     * 处理所有不可知异常
     *
     * @param e 异常
     * @return json结果
     */
    @exceptionhandler(exception.class)
    @responsebody
    public apiresult handleexception(exception e) {
        // 打印异常堆栈信息
        log.error(e.getmessage(), e);
        return apiresult.of(resultcode.unknown_error);
    }
    /**
     * 处理所有业务异常
     *
     * @param e 业务异常
     * @return json结果
     */
    @exceptionhandler(businessruntimeexception.class)
    @responsebody
    public apiresult handleopdruntimeexception(businessruntimeexception e) {
        // 不打印异常堆栈信息
        log.error(e.getmsg());
        return apiresult.of(e.getresultcode());
    }
}

二、测试

1、测试 testcontroller

package com.tao.smp.controller;
import com.tao.smp.exception.businessruntimeexception;
import com.tao.smp.exception.resultcode;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
/**
 * 测试异常的抛出
 */
@controller
@requestmapping("/")
public class testcontroller {
    /**
     * 测试返回异常信息
     * @return
     */
    @getmapping("/exception")
    public string returnexceptioninfo() {
        if (1 != 2) {
            // 用户民错误或不存在异常
            throw new businessruntimeexception(resultcode.username_error);
        }
        return "success";
    }
}

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

(0)

相关文章:

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

发表评论

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