'Spring Boot controller endpoint request with invalid characters must throw 400 instead 500?
I'm testing a Spring Boot Microservice and performing some security checking.
When I try to send a request to the endpoint with invalid characters to the URL, e.g., https://server/api/dogs/%2500/puppies you noticed the "%2500" is invalid.
The service throws 500 Internal Server error and returns a message that there is an invalid character in the request.
Is there a way to validate the URL in the request in my Spring Boot application so that it will throw 400 Bad Request, instead of 500 Internal Server error.
Solution 1:[1]
You can use @ControllerAdvice annotation which supports the generic exception handler mechanism.
Controller advice allows you to use exactly the same exception handling techniques but apply them across the whole application, not just to an individual controller.
You can think of them as an annotation driven interceptor. (Look to learn more.)
@ControllerAdvice
class GlobalControllerExceptionHandler {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(IllegalArgumentException.class)
public void handleIllegalArgumentException() {
// Nothing to do ..
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Object> handleMethodArgumentNotValidException(
MethodArgumentNotValidException e, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("message", "...");
return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);
}
}
Note: The exceptions and return information here are examples. You can globally contain the exception appropriate for your own example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
