• 全局异常响应信息处理


    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);
        }
    }
  • 相关阅读:
    HZOJ 太阳神
    HZOJ Silhouette
    HZOJ Dash Speed
    HZOJ 巨神兵
    值得纪念的cspsAFO总结
    11月FLAG
    模板易错总结
    树 总结
    DP总结(优化等)
    代码低级错误总结
  • 原文地址:https://www.cnblogs.com/java-spring/p/13395916.html
Copyright © 2020-2023  润新知