GlobalExceptionHandler.java 1.97 KB
package com.glsx.exception;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.glsx.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author fengzhi
 * @version V1.0
 * @Description: 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 业务异常处理
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
        log.error("业务异常:" + e.getMessage());
        ApiException businessException = (ApiException) e;
        return businessException.getResultEntity();
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        //遍历参数异常的提示信息拼接返回
        List<String> errs = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());

        log.error("参数异常:" + errs);
        return ApiErrorMessage.ARGS_NULL.exception(errs).getResultEntity();
    }

    /**
     * 业务异常处理
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = InvalidFormatException.class)
    public Result InvalidFormatHandler(HttpServletRequest req, Exception e) {
        String errMsg = "jackson反序列化失败:" + e.getMessage();
        log.error(errMsg);
        return new ApiException(errMsg).getResultEntity();
    }


}