spring boot 全局异常处理

Posted 全力以赴001

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }
}

 

以上是关于spring boot 全局异常处理的主要内容,如果未能解决你的问题,请参考以下文章

Spring Boot-全局异常处理

峰哥说技术系列-9 Spring Boot ControllerAdvice处理全局异常 - 副本

Spring Boot2 系列教程(十三)Spring Boot 中的全局异常处理

spring boot 全局异常处理

Spring Boot系列SpringBoot全局异常处理数据校验

Spring Boot入门——全局异常处理