Master Spring Boot Customized Exceptions — A Practical Guide

“Over 97% of Java applications utilize custom exceptions for clearer, more precise error handling.”

Eidan Khan
JavaJams
3 min readApr 8, 2024

--

Detective Magnifying Code — Image generated by DALL-E

Custom exceptions are like the secret spices in a chef’s recipe — they give your error handling that special touch. They’re not just about catching errors; they’re about creating a narrative for what went wrong and guiding the user to a resolution.

A study by Harness reveals that “97% of logged error statements are caused by 3% of unique errors” in Java applications. This means that a handful of errors can cause the majority of problems. By implementing custom exceptions, you can address these frequent issues more effectively.

With custom exceptions, you can:

  • Pinpoint issues: Like a detective’s magnifying glass, they help you zoom in on the problem.
  • Communicate effectively: They speak to users with clarity, avoiding technical jargon.
  • Maintain control: They keep your application’s error responses consistent and predictable.

Did You Know? The Null Reference Cost Us Billions

In the realm of Java, the NullPointerException is the king of bugs, affecting 70% of production environments. Its infamy is such that Sir Charles Antony Richard Hoare, the inventor of the null reference, famously referred to it as his “billion-dollar mistake.” This single type of error has been responsible for countless system crashes and vulnerabilities over the years, emphasizing the importance of robust error handling in applications.

My Journey with Custom Exceptions

In my early days of Spring Boot development, I encountered a bug that was as elusive as a ghost. It was a service-level exception that provided no clear direction for resolution. After several hours of head-scratching, I implemented a custom exception that acted like a lighthouse, guiding me straight to the problem’s core. This experience was a turning point, teaching me the value of precise error reporting.

Enabling Custom Exceptions in Spring Boot

To harness the power of custom exceptions in Spring Boot, consider these steps as your roadmap:

  1. Craft Your Exception: Define your custom exception class. It’s like creating a character in a story — give it attributes that tell its tale.
  2. Advise Your Controllers: Use @ControllerAdvice or @RestControllerAdvice to offer wisdom to your controllers on how to handle these exceptions. The former is used in MVC applications where you return views, and the latter in RESTful services where you return JSON responses.
  3. Handle with Care: With @ExceptionHandler, you set up a safety net to catch specific exceptions. You can even catch multiple exceptions with one handler using syntax like @ExceptionHandler({CustomException1.class, CustomException2.class}).

Let’s dive into a snippet that illustrates a custom exception for a scenario where a book is not found in our library application:

// Custom 'BookNotFoundException' for when a book is missing
public class BookNotFoundException extends RuntimeException {
public BookNotFoundException(String title) {
super("Book not found: " + title);
}
}

// Service to handle the business logic
public class LibraryService {
public Book findBook(String title) {
// Logic to find the book
throw new BookNotFoundException(title);
}
}

// Global exception handler
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BookNotFoundException.class)
public ResponseEntity<Object> handleBookNotFound(
BookNotFoundException ex) {

Map<String, Object> body = new LinkedHashMap<>();
body.put("error", "Book Not Found");
body.put("message", ex.getMessage());

return new ResponseEntity<>(body, HttpStatus.NOT_FOUND);
}
}

Thank you for embarking on this journey through the realm of custom exceptions with me. Your engagement is the wind beneath my wings, inspiring me to share knowledge. If you’ve found value in this guide, please follow for more insights, clap to show your support, and share this story with friends who might find it enlightening.

--

--

Eidan Khan
JavaJams

🚀 Full-stack Dev | Tech Content Creator 📝 For more in-depth articles, tutorials, and insights, visit my blog at JavaJams.org.