GCastThrowing and Catching Custom Exceptions in a Java Spring Boot Application [GCast 91]
- Error checks move out of the controller into a custom exception. The previous episode put the validation in the controller; Giard likes to keep controllers as clean as possible. Now the service throws a custom exception carrying the error message, and the controller catches it.
- His custom exceptions are nearly always the same boilerplate. He puts them in their own exceptions folder. MissingArgumentsException extends Exception, adds the default serial version ID the parent expects, and has two constructors, one taking a string message and one taking a Throwable, each just calling super. He says 99% of his custom exceptions look like that; the class and its constructors must be public.
- Java requires every method that may throw it to declare that. The math service's add method checks for a null first or second number and throws the exception with a message. Its throws declaration then had to go on the interface, on a mock implementation from an earlier video, and on the GET method that also calls the add method, which otherwise failed with "unhandled exception type".
- The controller wraps the call in try/catch and returns 400. The sum variable is declared outside the try because it is used later. The catch takes the exception's message rather than hard-coding one, and returns a null sum with that message and HTTP 400; the person-name checks stay in the controller. Inputs of 10, 20 and "David" returned 30, and a missing number still returned a 400, now raised in the service.
- Exceptions from deep in a call chain reach one catch. Giard gives two reasons for the refactor despite near-identical output: a cleaner controller, and, more important in his view, that in real services calling other services, databases and the file system, an exception thrown anywhere bubbles up to the controller unless something swallows it on the way. He says the next video shows a simpler way using Spring itself.