All That Dev

Custom Error Handling for Invalid Integer or Boolean Input in Spring Boot GET Requests

November 8, 2024 | by Cícero Fabio

allthaedev.com.backgroud

In Spring Boot, you can customize error messages for validation by using the @Valid annotation along with a custom exception handler. However, it’s important to note that for a GET request, query parameters are typically not validated directly in the same way as request bodies. You can still catch invalid types and respond with a custom error message.

Here’s how you can achieve this:

Step 1: Create a Custom Exception Handler

You can create a class annotated with @ControllerAdvice to handle exceptions globally:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NumberFormatException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleNumberFormatException(NumberFormatException ex) {
        return new ResponseEntity<>("Custom Error: Please provide a valid integer.", HttpStatus.BAD_REQUEST);
    }
}

Step 2: Create Your Controller

In your controller, you can define a method that expects an integer parameter. If a string is passed, the NumberFormatException will be thrown, and the custom handler will catch it:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/api/validate")
    public String validateInput(@RequestParam int number) {
        return "Received number: " + number;
    }
}

Step 3: Test the Implementation

  • If you call the endpoint with a valid integer (e.g., /api/validate?number=5), you’ll receive a successful response.
  • If you call it with a string (e.g., /api/validate?number=abc), you’ll receive your custom error message:
Custom Error: Please provide a valid integer.

You can handle validation for a boolean parameter in a similar manner to how you would handle an integer. The key is to catch the IllegalArgumentException that is thrown when a string that cannot be converted to a boolean is passed.

Here’s how to set it up:

Step 1: Create a Custom Exception Handler

You can modify your existing global exception handler or create a new one to handle IllegalArgumentException specifically for boolean parameters:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(NumberFormatException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleNumberFormatException(NumberFormatException ex) {
        return new ResponseEntity<>("Custom Error: Please provide a valid integer.", HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity<String> handleIllegalArgumentException(IllegalArgumentException ex) {
        return new ResponseEntity<>("Custom Error: Please provide a valid boolean value (true/false).", HttpStatus.BAD_REQUEST);
    }
}

Step 2: Create Your Controller

In your controller, define a method that expects a boolean parameter. If a string that cannot be converted to a boolean is passed, the IllegalArgumentException will be thrown, and the custom handler will catch it:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/api/validateBool")
    public String validateBoolean(@RequestParam boolean flag) {
        return "Received boolean: " + flag;
    }
}

Step 3: Test the Implementation

  • If you call the endpoint with a valid boolean (e.g., /api/validateBool?flag=true or /api/validateBool?flag=false), you’ll receive a successful response.
  • If you call it with an invalid string (e.g., /api/validateBool?flag=abc), you’ll receive your custom error message:
Custom Error: Please provide a valid boolean value (true/false).

Final Thoughts

By using a @ControllerAdvice to handle NumberFormatException, you can provide a custom error message when the user passes a string instead of an integer in a GET request. This approach allows you to keep your controller clean and manage errors globally.

By adding a specific exception handler for IllegalArgumentException, you can provide a custom error message when the user passes an invalid string instead of a boolean in a GET request. This approach allows you to effectively manage errors and provide clear feedback to the client.

RELATED POSTS

View all

view all