springboot自定义异常

本文详细介绍如何在SpringBoot项目中实现自定义异常及其处理,包括自定义异常类的创建、异常处理控制器的配置,以及如何进行异常的统一返回。通过自定义异常,可以更灵活地控制前端接收到的错误信息,提升用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot自定义异常以及异常处理

 在web项目中,我们可能需要给前端返回不同的提示码。例如:401表示没有权限,500代表位置异常,200代表请求成功等。但是这些提示码远远不能满足我们返回给前端的提示,可能还需要我们自定义错误码给前端,前端获取相应的错误码以及错误信息,展示到页面中。

使用自定义异常可以解决这些返回值,利用自定义异常以及对异常的处理,可以在返回的时候自定义我们的返回码以及错误信息等。

一、自定义异常类

/**
 * @author: lxw
 * @Date: 2019/2/16 20:00
 * @email:
 * @Description: 自定义异常(继承运行时异常)
 */
public class ExceptionUtils extends RuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     * 错误编码
     */
    private int code;

    /**
     * 消息是否为属性文件中的Key
     */
    private boolean propertiesKey = true;

    /**
     * 构造一个基本异常.
     *
     * @param message 信息描述
     */
    public ExceptionUtils(String message) {
        super(message);
    }

    /**
     * 构造一个基本异常.
     *
     * @param code 错误编码
     * @param message   信息描述
     */
    public ExceptionUtils(int code, String message) {
        this(code, message, true);
    }

    /**
     * 构造一个基本异常.
     *
     * @param code 错误编码
     * @param message   信息描述
     */
    public ExceptionUtils(int code, String message, Throwable cause) {
        this(code, message, cause, true);
    }

    /**
     * 构造一个基本异常.
     *
     * @param code     错误编码
     * @param message       信息描述
     * @param propertiesKey 消息是否为属性文件中的Key
     */
    public ExceptionUtils(int code, String message, boolean propertiesKey) {
        super(message);
        this.setCode(code);
        this.setPropertiesKey(propertiesKey);
    }

    /**
     * 构造一个基本异常.
     *
     * @param code 错误编码
     * @param message   信息描述
     */
    public ExceptionUtils(int code, String message, Throwable cause, boolean propertiesKey) {
        super(message, cause);
        this.setCode(code);
        this.setPropertiesKey(propertiesKey);
    }

    /**
     * 构造一个基本异常.
     *
     * @param message 信息描述
     * @param cause   根异常类(可以存入任何异常)
     */
    public ExceptionUtils(String message, Throwable cause) {
        super(message, cause);
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public boolean isPropertiesKey() {
        return propertiesKey;
    }

    public void setPropertiesKey(boolean propertiesKey) {
        this.propertiesKey = propertiesKey;
    }

}

二、自定义异常处理

import com.modules.common.utils.RUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * @author: lxw
 * @Date: 2019/2/16 20:00
 * @email:
 * @Description: 自定义异常处理
 */
@RestControllerAdvice
public class RExceptionUtilsHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(ExceptionUtils.class)
    public RUtils handleRRException(ExceptionUtils e) {
        RUtils r = new RUtils();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        return r;
    }

    /**
     * 未找到路径异常处理
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public RUtils handlerNoFoundException(Exception e) {
        logger.error(e.getMessage(), e);
        return RUtils.error(404, "路径不存在,请检查路径是否正确");
    }

    /**
     * 数据库异常处理
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public RUtils handleDuplicateKeyException(DuplicateKeyException e) {
        logger.error(e.getMessage(), e);
        return RUtils.error("数据库中已存在该记录");
    }

    /**
     * 普通异常处理
     */
    @ExceptionHandler(Exception.class)
    public RUtils handleException(Exception e) {
        logger.error(e.getMessage(), e);
        return RUtils.error();
    }
}

三、自定义返回

package com.modules.common.utils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: lxw
 * @Date: 2019/2/19 11:19
 * @email:
 * @Description: 自定义返回值
 */
public class RUtils extends HashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    /**
     * 默认正常返回,使用new RUtils()就可以返回
     */
    public RUtils() {
        put("code", 0);
    }

    /**
     * 表示异常
     */
    public static RUtils error() {
        return error(500, "未知异常,请联系管理员");
    }

    public static RUtils error(String msg) {
        return error(500, msg);
    }

    /**
     * 自定义异常错误码
     */
    public static RUtils error(int code, String msg) {
        RUtils r = new RUtils();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    /**
     * 带信息的正常返回
     */
    public static RUtils ok(String msg) {
        RUtils r = new RUtils();
        r.put("msg", msg);
        return r;
    }

    public static RUtils ok(Map<String, Object> map) {
        RUtils r = new RUtils();
        r.putAll(map);
        return r;
    }

    public static RUtils ok() {
        return new RUtils();
    }

    @Override
    public RUtils put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}

四、测试输出

/**
 * @author: lxw
 * @Date: 2018/10/19 19:36
 * @email: 1229703575@qq.com
 * @Description: 测试文件
 */
@RestController
@RequestMapping("/")
public class TestController {
   /**
     * 测试自定义异常
     *
     * @return RUtils
     */
    @ApiOperation(value = "测试自定义异常", notes = "测试自定义异常")
    @GetMapping(value = "/exceptionTest")
    public RUtils exceptionTest() {
        String msg = new ExceptionUtils(500, "测试异常").getMessage();
        int errorCode = new ExceptionUtils(500, "测试异常").getCode();
        return RUtils.error(errorCode, msg);
    }     
}

五、输出结果

 

{"msg":"测试异常","code":500}

  

转载于:https://www.cnblogs.com/lxwthinker/p/10402965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值