温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

spring boot 全局异常处理方法汇总

发布时间:2020-10-04 20:55:02 来源:脚本之家 阅读:172 作者:全力以赴001 栏目:编程语言

这篇文章主要介绍了spring boot 全局异常处理方法汇总,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

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 {

  /**
   * 缺失请求参数处理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(MissingServletRequestParameterException.class)
  @ResponseBody
  public ResponseResult handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) {
    String message = "缺失请求参数" + e.getParameterName();
    return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
  }

  /**
   * 请求参数类型错误处理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(MethodArgumentTypeMismatchException.class)
  @ResponseBody
  public ResponseResult handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
    String message = "请求参数" + e.getName() + "类型错误";
    return ackTransfer(request, message, HttpStatus.BAD_REQUEST.value() + "", e);
  }

  /**
   * 参数类型错误异常类型处理
   *
   * @param e
   * @param request
   * @return
   */
  @ExceptionHandler(HttpMessageConversionException.class)
  @ResponseBody
  public ResponseResult handleHttpMessageNotReadableException(HttpMessageConversionException e, HttpServletRequest request) {
    String message = "参数类型错误";
    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);
  }

  /**
   * 处理运行时异常
   *
   * @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);
  }

  /**
   * 默认异常处理
   *
   * @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);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI