日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

在SpringBoot中系統異常和自定義的異常的統一處理

作者:ImisLi 更新時間: 2024-03-25 編程語言

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數據庫中存入數據,但是某一字段可能因為設置了唯一約束,導致字段重復會報一下錯誤:

原文鏈接:https://blog.csdn.net/ImisLi/article/details/132266436

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新