AI Hints
Home›Spring Boot Tutorial›@RestControllerAdvice, ProblemDetail and Practice: Clean Errors
Spring Boot · Lesson 81 of 120

Practice: Clean Errors

Your turn.

⏱ 2 min read▶ Video at 1:48:24🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

Let's practise error handling. A controller throws an Illegal Argument Exception, for a bad percentage. Right now, that becomes five hundred.

  • IllegalArgumentException
  • Bad percentage
  • Currently 500

The controller

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
@RestController
public 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;
    }
}

Turn it into a 400

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.

Show hint

ProblemDetail.forStatusAndDetail(HttpStatus.BAD_REQUEST, ex.getMessage())

Show solution
GlobalErrors.javajava
@RestControllerAdvice
public 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"
}

What module nine taught

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.

keyvalue
Rules@NotBlank, @Positive, @Size
Check@Valid
Handle@ExceptionHandler
Everywhere@RestControllerAdvice + ProblemDetail

Summary

Your API now checks its input, and explains every error clearly. That's the end of module nine. Next module, API design.

Key takeaways
  • Validation
  • Exception handlers
  • ProblemDetail
Next up: Controller, Service, Repository — three layers