zoukankan      html  css  js  c++  java
  • 全局异常响应信息处理

    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);
        }
    }
  • 相关阅读:
    浏览器兼容性问题
    浏览器对象的属性和方法
    js总结体会
    css样式总结体会
    HTML标签类总结
    如何自动化实现二级域名访问,类似博客
    php
    require.js
    gulp
    javascript
  • 原文地址:https://www.cnblogs.com/java-spring/p/13395916.html
Copyright © 2011-2022 走看看