You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不修改BigInteger类型的前提下处理无效输入或自定义反序列化异常?

解决方案

在不修改num字段BigInteger类型的前提下,可通过两种方式处理这类无效输入:

方案一:自定义Jackson反序列化器,拦截无效输入并自定义处理

通过自定义Jackson反序列化逻辑,在将JSON字符串转换为BigInteger时捕获格式错误,可选择返回默认值或抛出可控异常。

步骤1:实现自定义反序列化器

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.math.BigInteger;

public class SafeBigIntegerDeserializer extends JsonDeserializer<BigInteger> {
    @Override
    public BigInteger deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String value = p.getText();
        try {
            return new BigInteger(value);
        } catch (NumberFormatException e) {
            // 可自定义处理逻辑:比如返回默认值BigInteger.ZERO,或抛出自定义异常
            throw new IllegalArgumentException("num字段必须为有效整数格式");
        }
    }
}

步骤2:在实体类字段上绑定反序列化器

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Getter;
import lombok.Setter;
import java.math.BigInteger;

@Getter
@Setter
public class InputRequest {
    @JsonDeserialize(using = SafeBigIntegerDeserializer.class)
    private BigInteger num;
}

方案二:全局异常处理器捕获序列化异常

Spring会在JSON反序列化失败时抛出HttpMessageNotReadableException,通过全局异常处理器捕获该异常,返回自定义友好响应。

实现全局异常处理器

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<Map<String, Object>> handleJsonParseException(HttpMessageNotReadableException e) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", 400);
        // 根据异常信息针对性返回提示
        if (e.getMessage().contains("BigInteger")) {
            response.put("message", "num字段必须输入有效整数");
        } else {
            response.put("message", "请求参数格式错误");
        }
        return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST);
    }
}

内容的提问来源于stack exchange,提问作者Kaninchen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:35:17