溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot如何自定義異常并捕獲異常返給前端

發(fā)布時(shí)間:2021-11-15 09:08:32 來源:億速云 閱讀:717 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下springboot如何自定義異常并捕獲異常返給前端,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

背景

在開發(fā)中,如果用try catch的方式,每個(gè)方法都需要單獨(dú)實(shí)現(xiàn),為了方便分類異常,返回給前端,采用了@ControllerAdvice注解和繼承了RuntimeException的方式來實(shí)現(xiàn)。

實(shí)現(xiàn)內(nèi)容

捕獲了三類異常
1.業(yè)務(wù)異常

          BusinessException

2.系統(tǒng)異常 

        SystemException

3.其他異常

        利用@ExceptionHandler(RuntimeException.class)去捕獲

ExceptionAdvice類捕獲以上三類異常,并返回自定義類型格式數(shù)據(jù)

實(shí)現(xiàn)代碼

業(yè)務(wù)異常BusinessException類實(shí)現(xiàn)方式,繼承RuntimeException

public class BusinessException extends  RuntimeException {
	/**
	 * 錯(cuò)誤編碼
	 */
	private String code;
 
	public BusinessException() {
		super();
	}
 
	public BusinessException(String message) {
		super(message);
	}
 
	public BusinessException(String code, String message) {
		super(message);
		this.code = code;
	}
 
	public BusinessException(Throwable cause) {
		super(cause);
	}
 
	public BusinessException(String message, Throwable cause) {
		super(message, cause);
	}
 
	public BusinessException(String message, Throwable cause,
							 boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}
 
	public String getCode() {
		return code;
	}
 
	public void setCode(String code) {
		this.code = code;
	}
 
	@Override
	public String getMessage() {
		return super.getMessage();
	}
 
	@Override
	public String toString() {
		return this.code + ":" + this.getMessage();
	}
}

系統(tǒng)異常SystemException類實(shí)現(xiàn)方式,繼承RuntimeException,同業(yè)務(wù)異常類的實(shí)現(xiàn)方式一樣

public class SystemException extends  RuntimeException {
	/**
	 * 錯(cuò)誤編碼
	 */
	private String code;
 
	public SystemException() {
		super();
	}
 
	public SystemException(String message) {
		super(message);
	}
 
	public SystemException(String code, String message) {
		super(message);
		this.code = code;
	}
 
	public SystemException(Throwable cause) {
		super(cause);
	}
 
	public SystemException(String message, Throwable cause) {
		super(message, cause);
	}
 
	public SystemException(String message, Throwable cause,
                           boolean enableSuppression, boolean writableStackTrace) {
		super(message, cause, enableSuppression, writableStackTrace);
	}
 
	public String getCode() {
		return code;
	}
 
	public void setCode(String code) {
		this.code = code;
	}
 
	@Override
	public String getMessage() {
		return super.getMessage();
	}
 
	@Override
	public String toString() {
		return this.code + ":" + this.getMessage();
	}
}

ExceptionAdvice類,采用增強(qiáng)Controller注解 @ControllerAdvice的方式來實(shí)現(xiàn)

1.方法名稱和返回類型都可以根據(jù)自己需要定義;

2.采用注解@ExceptionHandler,就是捕獲的異常類型,我們只需要把需要捕獲異常類型寫進(jìn)來就好

springboot如何自定義異常并捕獲異常返給前端

 ExceptionAdvice 具體代碼實(shí)現(xiàn)如下:

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;
 
@ControllerAdvice
public class ExceptionAdvice {
    public static Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
 
    @ResponseBody
    @ExceptionHandler(SystemException.class)
    public Result handleException(Exception e) {
        logger.error("系統(tǒng)異常信息:", e);
        Result result = new Result();
        if (e instanceof BusinessException) {
            e = (BusinessException) e;
            result.setCode(((BusinessException) e).getCode());
        }
        result.setFailed(e.getMessage());
        return result;
    }
 
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result handleException(RuntimeException e) {
        logger.error("異常信息:", e.getMessage());
        Result result = new Result();
        result.setStatus(500);
        result.setMessage(e.getMessage());
        return result;
    }
 
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public AjaxJson doBusinessException(Exception e) {
        AjaxJson ajaxJson = new AjaxJson();
        logger.error("業(yè)務(wù)異常消息:", e.getMessage());
        ajaxJson.setRet(-1);
        ajaxJson.setMsg(e.getMessage());
        return ajaxJson;
    }
 
}

測(cè)試代碼

1.我們捕獲一個(gè)業(yè)務(wù)異常BusinessException,輸出aaa

springboot如何自定義異常并捕獲異常返給前端

 springboot如何自定義異常并捕獲異常返給前端

2.捕獲系統(tǒng)異常

throw new SystemException("aaaa");

3.其他的try catch的異常,這個(gè)就可以捕獲了 

springboot如何自定義異常并捕獲異常返給前端

以上是“springboot如何自定義異常并捕獲異常返給前端”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI