背景

这是继上一篇之后的第二弹
经常在报警群里看到这样的消息

xx
dev
3AAB09A5858A4FDDB40F2CACA991ECCF
exceptionHandler, error:Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: "aaaa"
error:Request method 'GET' not supported
error:JSON parse error: Can not deserialize value of type java.lang.Integer from String "%1": not a valid Integer value; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.lang.Integer from String "%1": not a valid Integer value

解决方法

在解决json解析异常的时候发现HttpMessageNotReadableException 异常会包含请求体缺失异常和json解析异常。

@ExceptionHandler(HttpMessageNotReadableException.class)
@ResponseBody
public Result handleMissingRequestBody(HttpMessageNotReadableException ex) {
    if (isJsonParseError(ex)) {
        // 如果不是 "body缺失" 异常,则继续抛出以让其他异常处理器处理
        log.error("json 解析异常: {}", ex.getMessage(), ex);
        return Result.buildErrorResult(ex.getMessage());
    }
    if (isJsonConvertError(ex)) {
        log.error("json 参数类型匹配异常: {}", ex.getMessage(), ex);
        return Result.buildErrorResult(ex.getMessage());
    }
    log.error("body缺失异常: {}", ex.getMessage(), ex);
    return Result.buildErrorResult("required request body is missing");
}

private boolean isJsonParseError(HttpMessageNotReadableException ex) {
    return (ex.getRootCause() instanceof JsonParseException);
}

private boolean isJsonConvertError(HttpMessageNotReadableException ex) {
    Throwable rootCause = ex.getRootCause();
    // rootCause instanceof JsonMappingException 如果缺少字段也要捕获就加这个
    return (rootCause instanceof InvalidFormatException);
}

@ExceptionHandler(MissingServletRequestParameterException.class)
@ResponseBody
public Result<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
    log.error("query缺失异常:{}", ex.getMessage(), ex);
    return Result.buildErrorResult("required parameter is not present");
}


@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
public Result handleRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex) {
    log.error("请求方法不匹配异常: {}", ex.getMessage(), ex);
    return Result.buildErrorResult(ex.getMessage());
}

完整代码

小生听雨园此处内容已经被作者隐藏,请输入验证码查看内容
验证码:
请关注本站微信公众号,回复“验证码”,获取验证码。在微信里搜索“小生听雨园”或者“manners_maketh_man__”或者微信扫描右侧二维码都可以关注本站微信公众号。

站点统计

  • 文章总数:309 篇
  • 分类总数:19 个
  • 标签总数:191 个
  • 运行天数:1009 天
  • 访问总数:129590 人次

浙公网安备33011302000604

辽ICP备20003309号