SoFunction
Updated on 2025-04-26

JSON numerical overflow problem in Spring Boot from error reporting to elegant solution

1. Question background: Why did my interface suddenly report an error?

Suppose you are developing a Spring Boot interface that receives JSON requests like this:

{
  "size": 111111111111111111111
}

Then suddenly receive feedback from users:An error has been reported for request!Check the log and found a dazzling exception:

JSON parse error: Numeric value (111111111111111111111) out of range of int

Translated into "human words":Front-end transmissionsizeThe value is too large, use it for the backendintWhen receiving type, it is exceededintThe range (-2147483648 ~ 2147483647) caused JSON parsing to fail!

2. Why does this error occur?

1. "Capacity" limit for Java data types

  • intThe maximum type can only be expressed2147483647
  • When the value in JSON exceeds this range,intIf you can't install it, an overflow error will be triggered.

2. Who is "making trouble" behind the scenes?

  • Jackson Library: Spring Boot uses Jackson to parse JSON by default.
    When the field type isintorInteger, but when the JSON value is too large, Jackson will directly throw an exception!

3. Solution: Three steps to complete

Step 1: Modify the field type (remedy the root cause)

DirectlysizeThe field type of   is changed toLong, solve the problem in one step!

public class EsSearchResultRequest {
    private Long size;  // ✅ Change to Long type    // Other fields...}

Why is it effective?

  • LongThe scope of   is-9223372036854775808 ~ 9223372036854775807, enough to accommodate super large values.

Step 2: Global exception handling (elegant prompt)

existGlobalExceptionHandlerCatch exceptions in   and return friendly prompts:

@ExceptionHandler()
public ResponseEntity<String> handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
    String errorMessage = "The request parameter format is incorrect, please check the value range";
    // Extract the specific cause of error (optional)    if (() instanceof JsonMappingException) {
        errorMessage = ().getMessage(); 
    }
    return ().body(errorMessage);
}

Effect example:The front-end received a prompt:

Numeric value (111111111111111111111) out of range of int

Step 3: Data verification (defensive programming)

If the business requiressizeIt must be a smaller value, and verification logic can be added:

public class EsSearchResultRequest {
    @Min(value = 1, message = "size is 1")
    @Max(value = 1000, message = "size maximum is 1000")
    private Long size;
    // Other fields...}

Prompt when verification fails:

size The largest 1000

4. Extended knowledge: Why not use Integer?

type scope Recommended scenarios
int -2³¹ ~ 2³¹-1 Decimal value (such as status code)
Long -2⁶³ ~ 2⁶³-1 Large values ​​(such as ID, timestamp)
BigInteger Unlimited (memory limit) Astronomical figures

Rules of thumb:

  • When the value is not determined, use it firstLong
  • Never useintStorage may be extremely large!

5. Frequently Asked Questions FAQ

1. Will the string transmitted on the front end report an error?

  • Won't! If JSON is insizeIt's a string"111111111111111111111", need to be used in the backendStringType reception, and then manually convert.

2. Do the database field type need to be changed?

  • ifsizeTo save it to the database (such as MySQL), remember to synchronously modify it toBIGINT, otherwise the insertion will fail!

3. Why does exception handling require HttpMessageNotReadableException to catch?

  • This is the "total exception" thrown by Spring when parsing the request body fails, covering all JSON parsing errors (such as type mismatch, format errors, etc.).

6. Summary: Guide to avoid pits

  • Design stage: Choose the appropriate data type according to the business scenario.
    • When you are uncertain, uselessLong
  • Coding stage
    • Add data verification (such as@Min@Max)。
    • Global exception handling, return friendly prompts.
  • Collaborative phase
    • Inform the front-end parameter range and format requirements.
    • Update the interface document and clarifysizeTypes and limitations.

This is the article about the JSON numerical overflow problem in Spring Boot from error to elegant solutions. For more related content on Spring Boot JSON numerical overflow problem, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!