背景
这是继上一篇之后的第二弹
经常在报警群里看到这样的消息
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());
}

 
													 
													 
													