欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時間:2022年02月23日 10:22:52   作者:maybe宸  
這篇文章主要介紹了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è)務(wù)邏輯時拋出自定義異常,這個時候需要自定義業(yè)務(wù)異常類。

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

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

public class BusinessException extends RuntimeException{?
}

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

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

所以如下:

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è)務(wù)異常和錯誤碼之間的匹配。所以在優(yōu)化一下。

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

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

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è)務(wù)異常類:

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è)務(wù)異常:"+e.getMessage());
?? ??? ??? ?BusinessException businessException = (BusinessException)e;
?? ??? ??? ?return ResultUtil.error(businessException.getCode(), businessException.getMessage());
?? ??? ?}
?? ??? ?//未知錯誤
?? ??? ?return ResultUtil.error(-1, "系統(tǒng)異常:\\n"+e);
?? ?}?? ?
}

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

全局異常處理配置

springboot Restful使用

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

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

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

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

/**
 * 異常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響應(yīng)狀態(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);
    }
    /**
     * 填充異常響應(yīng)消息
     * 
     * @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;
? ? ? }
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java超詳細介紹抽象類與接口的使用

    Java超詳細介紹抽象類與接口的使用

    在類中沒有包含足夠的信息來描繪一個具體的對象,這樣的類稱為抽象類,接口是Java中最重要的概念之一,它可以被理解為一種特殊的類,不同的是接口的成員沒有執(zhí)行體,是由全局常量和公共的抽象方法所組成,本文給大家介紹Java抽象類和接口,感興趣的朋友一起看看吧
    2022-05-05
  • java實現(xiàn)文件拷貝的七種方式

    java實現(xiàn)文件拷貝的七種方式

    這篇文章主要介紹了java實現(xiàn)文件拷貝的七種方式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-02-02
  • Maven中設(shè)置阿里云鏡像的全流程

    Maven中設(shè)置阿里云鏡像的全流程

    在Maven項目中,配置阿里云鏡像可以顯著提高依賴下載的速度和穩(wěn)定性,以下是詳細步驟,包括準備工作、修改settings.xml文件、驗證配置以及實際案例和示例代碼,通過這些步驟,你可以輕松地將Maven配置為使用國內(nèi)的鏡像源
    2025-02-02
  • java實現(xiàn)撲克牌分發(fā)功能

    java實現(xiàn)撲克牌分發(fā)功能

    這篇文章主要為大家詳細介紹了java實現(xiàn)撲克牌分發(fā),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-05-05
  • 淺析Java中局部變量與成員變量同名解決技巧

    淺析Java中局部變量與成員變量同名解決技巧

    在剛開始學習Java的時候,就了解了Java基礎(chǔ)中的變量,雖然知道這個以后會經(jīng)常用到,但沒想到了基本語法這里,竟然又冒出來了成員變量和局部變量。變來變?nèi)ヌ菀鬃屓烁銜灹?,今天我們就挑揀出來梳理一下?/div> 2016-07-07
  • Java如何利用Easyexcel動態(tài)導(dǎo)出表頭列

    Java如何利用Easyexcel動態(tài)導(dǎo)出表頭列

    這篇文章主要介紹了Java利用Easyexcel動態(tài)導(dǎo)出表頭列的實例,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • Java基礎(chǔ)泛型詳情

    Java基礎(chǔ)泛型詳情

    這篇文章主要介紹了Java基礎(chǔ)泛型詳情,泛型是JDK5中引入的特性,它提供了編譯時類型安全檢測機制,該機制允許在編譯時檢測到非法的類型,下面文章的詳細介紹,需要的朋友可以參考一下
    2022-04-04
  • Java如何根據(jù)根據(jù)IP地址獲取省市

    Java如何根據(jù)根據(jù)IP地址獲取省市

    這篇文章主要為大家詳細介紹了兩種在Java中獲取IP地址對應(yīng)地理位置信息的方法,分別是使用ip2region庫和GeoIP庫,感興趣的小伙伴可以了解下
    2025-01-01
  • springboot動態(tài)調(diào)整日志級別的操作大全

    springboot動態(tài)調(diào)整日志級別的操作大全

    這篇文章主要介紹了springboot動態(tài)調(diào)整日志級別的方法,本文通過實例圖文相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-10-10
  • Java中斷線程的方法

    Java中斷線程的方法

    這篇文章主要介紹了Java中斷線程的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2017-05-05

最新評論