异常解决:swagger2.9.2 报java.lang.NumberFormatException: For input string: ““...

异常解决:swagger2.9.2 报java.lang.NumberFormatException: For input string: “”…


springfox-swagger 2.9.2 内置的swagger-models1.5.20 会引起Long类型格式转换异常,报错如下

java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) ~[na:1.8.0_181]
	at java.lang.Long.parseLong(Long.java:601) ~[na:1.8.0_181]
	at java.lang.Long.valueOf(Long.java:803) ~[na:1.8.0_181]
	at io.swagger.models.parameters.AbstractSerializableParameter.getExample(AbstractSerializableParameter.java:412) ~[swagger-models-1.5.20.jar:1.5.20]
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]

这段报错的意思是,在将空串"",转换为Long类型时出现异常

解决方法一

对Long类型上的参数或属性上使用swagger注解时,指定example的值为数值型,比如

@ApiModelProperty(value = "公园",example="1", required = true)
private Long parkId;

具体原因:

项目中很多地方都使用了swagger注解,但对Long类型添加注解时未指定example值,比如

	//-------某个字段是Long类型的 这里未指定example的值,默认是空串 ""
	@ApiModelProperty(value = "公园", required = true)
	private Long parkId;

进入AbstractSerializableParameter类查看 getExample()方法

    @JsonProperty("x-example")
    public Object getExample() {
        // 如果example未指定值,默认是 example=""
        if (example == null) {
            return null;
        }
        try {
            // 这里的 equals():只要参数不为null,并且是一个String类型,就返回true.
            // 判断被注解(属性,参数)的类型,进入第一个if内。 Long.valueOf("")-->抛出NumberFormatException异常被捕获
            if (BaseIntegerProperty.TYPE.equals(type)) {
                return Long.valueOf(example);
            } else if (DecimalProperty.TYPE.equals(type)) {
                return Double.valueOf(example);
            } else if (BooleanProperty.TYPE.equals(type)) {
                if ("true".equalsIgnoreCase(example) || "false".equalsIgnoreCase(defaultValue)) {
                    return Boolean.valueOf(example);
                }
            }
        } catch (NumberFormatException e) {
            LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", defaultValue, type), e);
        }
        return example;
    }

复现异常

public static void main(String[] args) {
		long l = Long.valueOf("");
		System.out.println(l);
}
// 报错
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:601)
	at java.lang.Long.valueOf(Long.java:803)
	at com.lianxin.werm.api.resource.room.RoomForm.main(RoomForm.java:124)
解决方法二

将swagger-models1.5.20 版本升到1.5.22

			<dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-swagger2</artifactId>
                <version>2.9.2</version>
                <!-- 排除自带的1.5.20版本-->
                <exclusions>
                    <exclusion>
                        <groupId>io.swagger</groupId>
                        <artifactId>swagger-models</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
			<!-- 使用1.5.22-->
            <dependency>
                <groupId>io.swagger</groupId>
                <artifactId>swagger-models</artifactId>
                <version>1.5.22</version>
            </dependency>

新版对这个问题进行了修复,查看getExample()

如果example="" ,直接返回

    @JsonProperty("x-example")
    public Object getExample() {
        // example不为null 同时不为空串          这里的isEmpty():判断是否是空串
        if (this.example != null && !this.example.isEmpty()) {
            try {
                if ("integer".equals(this.type)) {
                    return Long.valueOf(this.example);
                }

                if ("number".equals(this.type)) {
                    return Double.valueOf(this.example);
                }

                if ("boolean".equals(this.type) && ("true".equalsIgnoreCase(this.example) || "false".equalsIgnoreCase(this.defaultValue))) {
                    return Boolean.valueOf(this.example);
                }
            } catch (NumberFormatException var2) {
                LOGGER.warn(String.format("Illegal DefaultValue %s for parameter type %s", this.defaultValue, this.type), var2);
            }
            return this.example;
        } else {
            // 如果example="" 直接返回
            return this.example;
        }
    }
### 解决 Swagger 启动时 `java.lang.NumberFormatException` 异常 当遇到 `java.lang.NumberFormatException: For input string: ""` 错误时,表明程序尝试将空字符串转换为数值类型。此问题通常发生在参数验证或数据绑定阶段。 #### 原因分析 该异常的根本原因在于试图解析一个空字符串 (`""`) 作为数字类型的输入[^1]。具体来说,在 API 请求路径中的某些参数可能未被正确传递或接收为空值,而这些参数预期应为整数或其他数值型数据。 #### 解决策略 ##### 参数校验增强 为了防止此类错误的发生,可以在控制器层面对传入的参数做更严格的检验: ```java @ResponseBody @ApiOperation(value = "根据ID获取订单配置表信息") @ApiImplicitParams({ @ApiImplicitParam( name = "id", value = "订单ID, 必填项且需为有效正整数", dataType = "integer", paramType = "path", required = true, defaultValue = "0" ) }) @RequestMapping(value = "/info/{id}", method = RequestMethod.GET) public ResponseEntity<?> info(@PathVariable("id") String idStr){ try { int id = Integer.parseInt(idStr); if (id <= 0) throw new IllegalArgumentException("ID must be positive"); Optional<ApsOrderConfigEntity> resultOpt = apsOrderConfigService.findById(id); return resultOpt.map(result -> ResponseEntity.ok(new ResponseWrapper<>("apsOrderConfig", result)) ).orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ErrorWrapper<>(HttpStatus.NOT_FOUND.value(), "Resource not found")) ); } catch(NumberFormatException e) { // 处理非数字的情况 return ResponseEntity.badRequest().body(new ErrorWrapper<>(HttpStatus.BAD_REQUEST.value(), "Invalid ID format")); } } ``` 上述代码通过捕获并处理潜在的 `NumberFormatException` 来避免应用崩溃,并返回恰当的状态码给客户端告知其请求存在问题[^3]。 另外一种方式是在实体类上定义更为严谨的数据约束条件来预防非法数据进入业务逻辑层面之前就被拦截下来: ```java import javax.validation.constraints.Min; //... class ApsOrderConfigDTO { @Min(1L)// 确保最小值至少为1 private Long id; // getter setter... } ``` 这样即使前端传来不合法的数据也会由框架自动检测到并给出相应的提示而不是直接抛出低级异常[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值