溫馨提示×

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

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

spring boot 全局異常處理方法匯總

發(fā)布時(shí)間:2020-10-04 20:55:02 來源:腳本之家 閱讀:168 作者:全力以赴001 欄目:編程語言

這篇文章主要介紹了spring boot 全局異常處理方法匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

import cn.sisyphe.framework.web.exception.DataException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ming
 * @desc 全局異常處理類
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

  /**
   * 缺失請(qǐng)求參數(shù)處理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(MissingServletRequestParameterException.class)
  @ResponseBody
  public ResponseResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) {
    String message = "缺失請(qǐng)求參數(shù)" + e.getParameterName();
    return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
  }

  /**
   * 請(qǐng)求參數(shù)類型錯(cuò)誤處理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(MethodArgumentTypeMismatchException.class)
  @ResponseBody
  public ResponseResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
    String message = "請(qǐng)求參數(shù)" + e.getName() + "類型錯(cuò)誤";
    return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
  }

  /**
   * 參數(shù)類型錯(cuò)誤異常類型處理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(HttpMessageConversionException.class)
  @ResponseBody
  public ResponseResult handleHttpMessageNotReadableException(HttpMessageConversionException e, HttpServletRequest request) {
    String message = "參數(shù)類型錯(cuò)誤";
    return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
  }

  /**
   * 空指針異常處理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(NullPointerException.class)
  @ResponseBody
  public ResponseResult handleNullPointerException(NullPointerException e, HttpServletRequest request) {
    String message = "空指針異常";
    return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e, true);
  }

  /**
   * MethodArgumentNotValidException 異常處理
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(MethodArgumentNotValidException.class)
  @ResponseBody
  public ResponseResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
    StringBuilder errorMsg = new StringBuilder();
    BindingResult re = e.getBindingResult();
    for (ObjectError error : re.getAllErrors()) {
      errorMsg.append(error.getDefaultMessage()).append(",");
    }
    errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
    return ackTransfer(request, errorMsg.toString(), "-1", e, false);
  }

  /**
   * 綁定異常處理
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(BindException.class)
  @ResponseBody
  public ResponseResult handleBindException(BindException e,HttpServletRequest request){
    BindingResult result = e.getBindingResult();
    StringBuilder errorMsg = new StringBuilder();
    for (ObjectError error : result.getAllErrors()) {
      errorMsg.append(error.getDefaultMessage()).append(",");
    }
    errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
    return ackTransfer(request, errorMsg.toString(), "-1", e, false);
  }


  /**
   * 自定義異常類型異常消息處理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler({DataException.class})
  @ResponseBody
  public ResponseResult handleDataException(DataException e, HttpServletRequest request) {
    String message = e.getErrorMessage();
    String code = e.getErrorCode();
    return ackTransfer(request, code, message, e, true);
  }

  /**
   * 處理運(yùn)行時(shí)異常
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler({RuntimeException.class})
  @ResponseBody
  public ResponseResult handleRuntimeException(RuntimeException e, HttpServletRequest request) {
    return ackTransfer(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value() + "", e, true);
  }

  /**
   * 默認(rèn)異常處理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(Exception.class)
  @ResponseBody
  public ResponseResult handleException(Exception e, HttpServletRequest request) {
    return ackTransfer(request, e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR.value() + "", e, true);
  }

  private ResponseResult ackTransfer(HttpServletRequest request, String message, String code, Exception e, boolean printStackTrace) {
    ResponseResult result = new ResponseResult();
    result.setCode(code);
    result.setMessage(message);
    if (printStackTrace) {
      log.error(message, e);
    } else {
      log.error(message);
    }
    return result;
  }

  private ResponseResult ackTransfer(HttpServletRequest request, String message, String code, Exception e) {
    return ackTransfer(request, message, code, e, false);
  }
}

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

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

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

AI