Price takes a price, and a percent. A percent outside nought to one hundred, throws an Illegal Argument Exception. Otherwise, it returns the new price.
PriceController.javajava
@RestControllerpublic class PriceController { @GetMapping("/price") public String price(@RequestParam double price, @RequestParam int percent) { if (percent < 0 || percent > 100) { throw new IllegalArgumentException("Percent must be between 0 and 100"); } return "New price: " + Math.round(price * (100 - percent)) / 100.0; }}
Your turn. Pause the video, and try this. Write a controller advice that turns Illegal Argument Exception into four hundred. Return a Problem Detail, with the title invalid request. Here is one solution. The handler builds a Problem Detail, from the exception's message. Twenty percent works. And one hundred and fifty percent gets a clean four hundred, explaining the rule.
✍️ Exercise: Turn it into a 400
Add @RestControllerAdvice GlobalErrors: IllegalArgumentException → ProblemDetail, 400, title "Invalid request", detail = the message.
@RestControllerAdvicepublic class GlobalErrors { @ExceptionHandler(IllegalArgumentException.class) public ProblemDetail badArgument(IllegalArgumentException ex) { ProblemDetail problem = ProblemDetail.forStatusAndDetail( HttpStatus.BAD_REQUEST, ex.getMessage()); problem.setTitle("Invalid request"); return problem; }}
Output
$ curl "localhost:8080/price?price=10&percent=20"
New price: 8.0
$ curl "localhost:8080/price?price=10&percent=150"
{
"title":"Invalid request",
"status":400,
"detail":"Percent must be between 0 and 100"
}
Never trust input. Constraint annotations describe the rules, and at Valid checks them. Exception handlers turn failures into clear responses. A controller advice handles them for the whole app. And Problem Detail is the standard format.