MethodArgumentTypeMismatchException异常捕捉

- 线上bug异常捕捉

- 背景:上线的时候发现一个bug,参数类型定义是一个Long型,但是前端传递过来的参数是一个undefined,导致解析失败。但是查看日志打印只显示类型转换错误(MethodArgumentTypeMismatchException),也不清楚调的是哪个接口.于是调整了一下日志捕捉代码。

private final static String ERROR_MSG = "服务器开小差啦!";


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResponseData<Object> methodNotSupportedHandler(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        log.error("url:{} -> 请求方式不正确:{}", request == null ? null : request.getRequestURL(), e);
        return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseData<Object> paramErrorHandler(Exception e, HttpServletRequest request) {
        log.error("url:{} -> 参数异常:{}", request == null ? null : request.getRequestURL(), e);
        return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMessage());
    }

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseData<Object> mismatchErrorHandler(MethodArgumentTypeMismatchException e) {
        log.error("参数转换失败,方法:" + Objects.requireNonNull(e.getParameter().getMethod()).getName() + ",参数:" +
                e.getName() + ",信息:" + e.getLocalizedMessage());
        return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    public ResponseData<Object> handler(BusinessException e, HttpServletRequest request) {
        log.error("url:{} -> 业务异常:{}", request == null ? null : request.getRequestURL(), e);
        Optional.ofNullable(request)
                .ifPresent(r -> {
                            TreeMap<String, String> reqMap = new TreeMap<>();
                            for (Map.Entry<String, String[]> me : r.getParameterMap().entrySet()) {
                                String key = me.getKey();
                                String value = me.getValue()[0];
                                reqMap.put(key, value);
                            }
                            log.error("user:{},mate:{},入参:{}",
                                    UserContext.getUserId(), MateContext.getMate(), JSON.toJSONString(reqMap));
                        }
                );
        return ResponseData.fail(e.getCode() == null ? ResponseCode.INTERNAL_ERROR.getCode() : e.getCode(), e.getMsg());
    }

    @ExceptionHandler(ParamException.class)
    public ResponseData<Object> handler(ParamException e, HttpServletRequest request) {
        log.error("url:{} -> 参数异常:{}", request == null ? null : request.getRequestURL(), e);
        Optional.ofNullable(request)
                .ifPresent(r -> {
                            TreeMap<String, String> reqMap = new TreeMap<>();
                            for (Map.Entry<String, String[]> me : r.getParameterMap().entrySet()) {
                                String key = me.getKey();
                                String value = me.getValue()[0];
                                reqMap.put(key, value);
                            }
                            log.error("user:{},mate:{},入参:{}",
                                    UserContext.getUserId(), MateContext.getMate(), JSON.toJSONString(reqMap));
                        }
                );
        return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMsg());
    }

    /**
     * 配合Assert使用,香
     *
     * @param e       e
     * @param request request
     * @return object
     */
    @ExceptionHandler({IllegalStateException.class, IllegalArgumentException.class})
    public ResponseData<Object> handler(RuntimeException e, HttpServletRequest request) {
        log.error("url:{} -> 业务异常:{}", request == null ? null : request.getRequestURL(), e);
        return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), e.getMessage());
    }

    @ExceptionHandler
    public ResponseData<Object> handler(Exception e, HttpServletRequest request) {
        log.error("url:{} -> 错误:{}", request == null ? null : request.getRequestURL(), e);

        Optional.ofNullable(request)
                .ifPresent(r -> {
                            TreeMap<String, String> reqMap = new TreeMap<>();
                            for (Map.Entry<String, String[]> me : r.getParameterMap().entrySet()) {
                                String key = me.getKey();
                                String value = me.getValue()[0];
                                reqMap.put(key, value);
                            }
                            log.error("user:{},mate:{},入参:{}",
                                    UserContext.getUserId(), MateContext.getMate(), JSON.toJSONString(reqMap));
                        }
                );
        return ResponseData.fail(ResponseCode.INTERNAL_ERROR.getCode(), ERROR_MSG);
    }

    /**
     * body参数
     *
     * @param e BindException
     */
    @ExceptionHandler(BindException.class)
    public ResponseData<Object> handlerBindException(BindException e) {
        StringBuilder msg = new StringBuilder();
        FieldError c = e.getBindingResult().getFieldErrors().get(0);
        msg.append(c.getDefaultMessage()).append(":").append(c.getRejectedValue());
        return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), msg.toString());
    }

    /**
     * 方法参数
     *
     * @param e ConstraintViolationException
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseData<Object> handlerConstraintViolationException(ConstraintViolationException e) {
        StringBuilder msg = new StringBuilder();
        ConstraintViolation<?> violation = e.getConstraintViolations().iterator().next();
        msg.append(violation.getMessage()).append(":").append(violation.getInvalidValue());
        return ResponseData.fail(ResponseCode.PARAM_INVALIDATE.getCode(), msg.toString());
    }

 

posted @ 2020-05-12 11:43  渠成  阅读(7539)  评论(0编辑  收藏  举报