成都网站建设设计

将想法与焦点和您一起共享

springboot全局异常处理方法汇总

这篇文章主要介绍了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);
  }
}

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


本文题目:springboot全局异常处理方法汇总
链接地址:http://chengdu.cdxwcx.cn/article/pjopdd.html