GlobalExceptionHandler.java 4.6 KB
package com.wondertek.exception;


import com.wondertek.util.ResultBean;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;


import java.util.List;

/**
 *  异常统一处理类
 * @author  luyafei
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final String LESS_REQUIRED_PARAM = "缺少必要参数";
    private static final String REQUEST_PARAMS_IS_NOT_ILLEGAL = "请求参数不合法";
    private static final String REQUEST_PARAMS_IS_NOT_EMPTY = "参数不能为空";
    private static final String REQUEST_PARAMS_MISMATCH = "请求参数类型不匹配";
    private static final String REQUEST_PARAMS_NUMBER_FORMAT_IS_ERROR = "请求参数数字类型解析异常";
    private static final String REQUEST_METHOD_NOT_SUPPORT = "当前requestMethod请求类型不支持";
    private static final String UNKNOWN = "未知异常";

    private static final String ERROR_MSG = ">>>获取异常信息:{}";
    /**
     * 业务异常
     *
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(value = ServiceException.class)
    public Object handlerServiceException(ServiceException e, HttpServletResponse response) {
        if (e.isNeedPrintStack()) {
            log.error(ERROR_MSG, e);
        } else {
            log.error(ERROR_MSG, e.getMessage());
        }
        return ResultBean.error(HttpStatus.BAD_REQUEST.value() + "", e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultBean unKnownException(Exception e) {
        return responseException(UNKNOWN, e);
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultBean methodArgumentNotValidException(MethodArgumentNotValidException e) {
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        if (!CollectionUtils.isEmpty(allErrors)) {
            return responseException(allErrors.get(0).getDefaultMessage(), e);
        }

        return responseException(LESS_REQUIRED_PARAM, e);
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultBean handleValidationException(ConstraintViolationException e) {
        for (ConstraintViolation<?> s : e.getConstraintViolations()) {
            return responseException(s.getMessage() + " : " + s.getInvalidValue(), e);
        }

        return ResultBean.error(REQUEST_PARAMS_IS_NOT_ILLEGAL);
    }



    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultBean handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        return responseException(e.getParameterName() + REQUEST_PARAMS_IS_NOT_EMPTY, e);
    }

    @ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultBean handlerMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        return responseException(e.getName() + REQUEST_PARAMS_MISMATCH, e);
    }

    @ExceptionHandler(value = NumberFormatException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultBean handlerNumberFormatException(NumberFormatException e) {
        return responseException(REQUEST_PARAMS_NUMBER_FORMAT_IS_ERROR, e);
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultBean handlerHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        return responseException(REQUEST_METHOD_NOT_SUPPORT, e);
    }

    private ResultBean responseException(String msg, Exception e) {
        log.info(e.getMessage(), e);
        return ResultBean.error(msg);
    }

}