溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

springboot如何實現(xiàn)全局異常處理及自定義異常類

發(fā)布時間:2022-02-23 11:46:50 來源:億速云 閱讀:169 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹springboot如何實現(xiàn)全局異常處理及自定義異常類,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!

全局異常處理及自定義異常類

全局異常處理

定義一個處理類,使用@ControllerAdvice注解。

@ControllerAdvice注解:控制器增強,一個被@Component注冊的組件。

配合@ExceptionHandler來增強所有的@requestMapping方法。

例如:@ExceptionHandler(Exception.class)  用來捕獲@requestMapping的方法中所有拋出的exception。

代碼:

@ControllerAdvice
public class GlobalDefultExceptionHandler {    
    //聲明要捕獲的異常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String defultExcepitonHandler(HttpServletRequest request,Exception e) {
        return “error”;
    }
}

這樣,全局異常處理類完畢。可以添加自己的邏輯。

然后還有一個問題,有的時候,我們需要業(yè)務邏輯時拋出自定義異常,這個時候需要自定義業(yè)務異常類。

定義class:BusinessException ,使他繼承于RuntimeException.

說明:因為某些業(yè)務需要進行業(yè)務回滾。但spring的事務只針對RuntimeException的進行回滾操作。所以需要回滾就要繼承RuntimeException。

public class BusinessException extends RuntimeException{ 
}

然后,現(xiàn)在來稍微完善一下這個類。

當我們拋出一個業(yè)務異常,一般需要錯誤碼和錯誤信息。有助于我們來定位問題。

所以如下:

public class BusinessException extends RuntimeException{
    //自定義錯誤碼
    private Integer code;
    //自定義構(gòu)造器,只保留一個,讓其必須輸入錯誤碼及內(nèi)容
    public BusinessException(int code,String msg) {
        super(msg);
        this.code = code;
    }
 
    public Integer getCode() {
        return code;
    }
 
    public void setCode(Integer code) {
        this.code = code;
    }
}

這時候,我們發(fā)現(xiàn)還有一個問題,如果這樣寫,在代碼多起來以后,很難管理這些業(yè)務異常和錯誤碼之間的匹配。所以在優(yōu)化一下。

把錯誤碼及錯誤信息,組裝起來統(tǒng)一管理。

定義一個業(yè)務異常的枚舉

public enum ResultEnum {
    UNKONW_ERROR(-1,"未知錯誤"),
    SUCCESS(0,"成功"),
    ERROR(1,"失敗"),
    ;    
    private Integer code;
    private String msg;    
    ResultEnum(Integer code,String msg) {
        this.code = code;
        this.msg = msg;
    }
 
    public Integer getCode() {
        return code;
    }
 
    public String getMsg() {
        return msg;
    }
}

這個時候,業(yè)務異常類:

public class BusinessException extends RuntimeException{    
    private static final long serialVersionUID = 1L;    
    private Integer code;  //錯誤碼 
    public BusinessException() {}    
    public BusinessException(ResultEnum resultEnum) {
        super(resultEnum.getMsg());
        this.code = resultEnum.getCode();
    }
    
    public Integer getCode() {
        return code;
    }
 
    public void setCode(Integer code) {
        this.code = code;
    }
}

然后再修改一下全局異常處理類:

@ControllerAdvice
public class GlobalDefultExceptionHandler {
    
    //聲明要捕獲的異常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public <T> Result<?> defultExcepitonHandler(HttpServletRequest request,Exception e) {
        e.printStackTrace();
        if(e instanceof BusinessException) {
            Log.error(this.getClass(),"業(yè)務異常:"+e.getMessage());
            BusinessException businessException = (BusinessException)e;
            return ResultUtil.error(businessException.getCode(), businessException.getMessage());
        }
        //未知錯誤
        return ResultUtil.error(-1, "系統(tǒng)異常:\\n"+e);
    }    
}

判斷這個是否是業(yè)務異常。和系統(tǒng)異常就可以分開處理了。 

全局異常處理配置

springboot Restful使用

@ControllerAdvice、@ExceptionHandler、@ResponseBody實現(xiàn)全局異常處理

  • @ControllerAdvice 注解定義全局異常處理類

  • @ExceptionHandler 指定自定義錯誤處理方法攔截的異常類型

同一個異常被小范圍的異常類和大范圍的異常處理器同時覆蓋,會選擇小范圍的異常處理器

1.定義異常業(yè)務類

/**
 * 異常VO
 * 
 * @date 2017年2月17日
 * @since 1.0.0
 */
public class ExceptionVO {
    private String errorCode;
    private String message;
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public String getErrorCode() {
        return errorCode;
    }
    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }
}

2.定義自定義異常

package exception;
/**
 * 無數(shù)據(jù)Exception
 *
 * @date 17/4/25
 * @since 1.0.0
 */
public class NotFoundException extends SystemException {
    public NotFoundException(String message) {
        super(message);
    }
}
/**
 * 系統(tǒng)異常
 * 
 * @date 2017年2月12日
 * @since 1.0.0
 */
public class SystemException extends RuntimeException {
    private static final long serialVersionUID = 1095242212086237834L;
    protected Object errorCode;
    protected Object[] args;
    public SystemException() {
        super();
    }
    public SystemException(String message, Throwable cause) {
        super(message, cause);
    }
    public SystemException(String message) {
        super(message);
    }
    public SystemException(String message, Object[] args, Throwable cause) {
        super(message, cause);
        this.args = args;
    }
    public SystemException(String message, Object[] args) {
        super(message);
        this.args = args;
    }
    public SystemException(Object errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }
    public SystemException(Object errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }
    public SystemException(Object errorCode, String message, Object[] args, Throwable cause) {
        super(message, cause);
        this.args = args;
        this.errorCode = errorCode;
    }
    public SystemException(Object errorCode, String message, Object[] args) {
        super(message);
        this.args = args;
        this.errorCode = errorCode;
    }
    public SystemException(Throwable cause) {
        super(cause);
    }
    public Object[] getArgs() {
        return args;
    }
    public Object getErrorCode() {
        return errorCode;
    }
}

3.定義全局異常處理類

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
import NotFoundException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import ExceptionVO;
/**
 * WEB異常處理器
 * 
 * @date 2017年2月16日
 * @since 1.0.0
 */
@ControllerAdvice("web") //指定異常處理期攔截范圍
public class WebExceptionHandler {
    static Logger LOG = LoggerFactory.getLogger(WebExceptionHandler.class);
    @Autowired
    private MessageSource messageSource;
    @ExceptionHandler(FieldException.class)
    @ResponseStatus(HttpStatus.CONFLICT) //指定http響應狀態(tài)
    @ResponseBody
    /**
     * 未找到數(shù)據(jù)
     *
     * @param e
     * @return
     */
    @ExceptionHandler(NotFoundException.class)//指定異常類型
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ResponseBody
    public ExceptionVO handleNotFoundException(NotFoundException e) {
        ExceptionVO vo = new ExceptionVO();
        fillExceptionVO(e, vo);
        return vo;
    }
    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    @ResponseBody
    public ExceptionVO handleSystemException(SystemException e) {
        ExceptionVO vo = new ExceptionVO();
        fillExceptionVO(e, vo);
        return vo;
    }
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public void globalError(Exception e) {
        LOG.error(e.getMessage(), e);
    }
    /**
     * 填充異常響應消息
     * 
     * @param e
     * @param vo
     */
    private void fillExceptionVO(SystemException e, ExceptionVO vo) {
        if (e.getMessage() != null) {
            String message = e.getMessage();
            try {
                message = messageSource.getMessage(e.getMessage(), e.getArgs(), LocaleContextHolder.getLocale());
            } catch (NoSuchMessageException ex) {
                ; // ignore
            }
            vo.setMessage(message);
        }
        vo.setErrorCode(String.valueOf(e.getErrorCode()));
    }
}

springboot 返回 ModelAndView

package exception.handler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
@Commpent
public class OverallExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
            Exception ex) {
        ModelAndView mav = new ModelAndView();
        System.out.println(ex.getMessage());
        mav.addObject("errMsg", ex.getMessage());
        mav.setViewName("error");
        return mav;
    }
}

其它方式:

@ControllerAdvice
public class GlobalExceptionHandler {
      @ExceptionHandler(value = Exception.class)
      public ModelAndView resolveException(HttpServletRequest request, Exception ex) throws Exception {
        ModelAndView mav = new ModelAndView();
        System.out.println(ex.getMessage());
        mav.addObject("errMsg", ex.getMessage());
        mav.setViewName("error");
        return mav;
      }
}

以上是“springboot如何實現(xiàn)全局異常處理及自定義異常類”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細節(jié)

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

AI