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);
        }
    }
  • 相关阅读:
    Python统计excel表格中文本的词频,生成词云图片
    springboot application.properties 常用完整版配置信息
    JAVA高级-面试题总结
    删除csdn上面自己上传的资源
    本博客背景特效源码
    我的自定义框架 || 基于Spring Boot || 第一步
    PYTHON 实现的微信跳一跳【辅助工具】仅作学习
    PM2守护babel-node
    记一个HOST引起的前端项目打不开的问题
    迭代器与iterable
  • 原文地址:https://www.cnblogs.com/java-spring/p/13395916.html
Copyright © 2011-2022 走看看