在SpringBoot中系统异常和自定义的异常的统一处理

1、自定义异常如何定义

package com.itheima.reggie.common;

/**
 * @ClassName CustomException
 * @Description 自定义异常
 * @Author LPS
 * @Date 2023/8/13 21:52
 */
public class CustomException extends RuntimeException{

    private String msg;

    public CustomException(String msg) {
        super(msg);
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

2、系统异常和自定义异常如何统一处理 (全局异常处理)

package com.itheima.reggie.handler;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName GlobExceptionHandler
 * @Description 全局异常处理器
 * @Author LPS
 * @Date 2023/8/13 21:57
 */
@RestControllerAdvice // 通知
public class GlobExceptionHandler {

    /**
     * 自定义异常的处理 通知
     *
     * @param e
     * @return
     */
    @ExceptionHandler(CustomException.class)
    private ResultInfo handlerCustomException(CustomException e) {
        return ResultInfo.error(e.getMsg()); // ResultInfo 统一结果的返回
    }


    /**
     * 系统异常的处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    private ResultInfo handlerSystemException(Exception e) {
        e.printStackTrace();
        return ResultInfo.error("系统出错了,请联系管理员");
    }

    /**
     * 应对mysql字段重复
     * @param d
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    private ResultInfo handlerDuplicateKeyException(DuplicateKeyException d){
        d.printStackTrace();
        return ResultInfo.error("您输入的内容存在...");
    }
}

如果往mysql数据库中存入数据,但是某一字段可能因为设置了唯一约束,导致字段重复会报一下错误:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值