全局异常响应信息处理

import com.dkjk.vo.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
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.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 捕捉其他所有异常
    @ExceptionHandler(value = Exception.class)
    public ResponseBean apiErrorHandlerException(HttpServletRequest request, Exception e) {
        String requestMethod = request.getMethod();
        String requestURI = request.getRequestURI();
        log.error("用" + requestMethod + "方式请求" + requestURI + "时出现异常", e);
        String eMessage = e.getMessage();
        if (e instanceof HttpRequestMethodNotSupportedException) {
            log.warn("请求方式错误,{}", e.getMessage());
            return new ResponseBean(400, "请求方式错误", eMessage);
        }
        if (e instanceof MissingServletRequestParameterException) {
            log.warn("参数错误,缺少参数,{}", e.getMessage());
            return new ResponseBean(400, "请求参数错误", e.getMessage());
        }
        if (e instanceof MethodArgumentNotValidException) {
            log.warn("参数错误,参数校验不通过导致的,{}", e.getMessage());
            MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) e;
            String defaultMessage = methodArgumentNotValidException.getBindingResult().getFieldError().getDefaultMessage();
            return new ResponseBean(400, "请求参数错误", defaultMessage);
        }
        if (e instanceof HttpMessageNotReadableException) {
            log.warn("参数错误,请求参数进行反序列化时导致的(参数类型不对应什么的),{}", e.getMessage());
            return new ResponseBean(400, "请求参数错误", e.getMessage());
        }
        return new ResponseBean(99999, "系统出现异常", null);
    }
}

 

posted @ 2020-07-29 11:05  劈天造陆  阅读(278)  评论(0编辑  收藏  举报