首页 > 其他分享 >同一处理前后参数类型不匹配导致的异常

同一处理前后参数类型不匹配导致的异常

时间:2022-12-20 18:57:28浏览次数:52  
标签:匹配 BigDecimal 同一 dd 参数 HttpMessageNotReadableException http 异常

参考资料地址1: HttpMessageNotReadableException异常原因和解决方法

参考资料地址2: HttpMessageNotReadableException错误

目录

01 起因

后端要求为BigDecimal类型,前端传了一个"1232-dd"字符串,造成类型转换失败,将异常抛给前端

异常信息

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.math.BigDecimal` from String "1232-dd": not a valid representation; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.math.BigDecimal` from String "1232-dd": not a valid representation

02 解决方案

由于还没有到Controller 层 就抛出了异常 我们是没有办法再自己的代码中校验参数来避免的,可以前端校验参数或者后端捕获掉此异常给出友好的提示

后端解决方案
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

     /**
     * 处理http请求参数转换异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    public ResultEntity<String> exceptionHandler(HttpMessageNotReadableException e) {
        log.warn("http请求参数转换异常:{}",e.getMessage());
        return ResultEntity.failed(1009,"参数格式错误");
    }
}

03 HttpMessageNotReadableException

请求参数转换异常

HttpMessageNotReadableException : Http消息不可读异常
大多都是在http controller 层 传入参数时所造成的不可解析的异常。

造成原因

  • 参数中传入的String类型的字段 在接收时 该映射字段时Integer类型
  • 当 Controller 曾 @RequestBody 接受参数时 调用接口时没有传参数时也会抛出此异常。

待调研,其他地方会不会抛出该异常

标签:匹配,BigDecimal,同一,dd,参数,HttpMessageNotReadableException,http,异常
From: https://www.cnblogs.com/lyn8100/p/16994886.html

相关文章