Software Development

How to implement a robust Global Exception Handler in Spring Boot using @ControllerAdvice?

BR Asked by Brandon Taylor · 21-01-2025
0 upvotes 12,895 views 0 comments
The question

We want to standardize our error responses across 20 different microservices. Currently, some return plain text, others return Whitelabel errors. What is the best way to use @RestControllerAdvice to catch custom exceptions and return a consistent JSON object with an error code, timestamp, and message for the frontend?

3 answers

0
KI
Answered on 23-01-2025

Standardizing error responses is vital for a good developer experience. You should create a custom ErrorDetails class that holds your standard fields (message, details, status, timestamp). Then, create a class annotated with @RestControllerAdvice. Inside, use @ExceptionHandler(YourCustomException.class) methods that return a ResponseEntity<ErrorDetails>. In my last project, we even included a unique "TraceID" from Sleuth/Micrometer in every error response. This allowed our frontend developers to give us a specific ID they saw in the UI, which we could then instantly look up in our logs to find the exact stack trace. It saved us countless hours of "trying to reproduce" bugs that only happened in production.

0
ST
Answered on 25-01-2025

How do you handle validation errors from the @Valid annotation, like MethodArgumentNotValidException, to make sure the field-level errors are also included in your custom JSON?

BR 26-01-2025

Steven, that's a great question. We override the handleMethodArgumentNotValid method from the ResponseEntityExceptionHandler class. Inside that override, we loop through the BindingResult to collect all the field errors and add them to a "validationErrors" map in our ErrorDetails object. This way, the frontend can see exactly which fields (like "email" or "password") failed the validation and display a helpful error message next to the input field, rather than just a generic "400 Bad Request" message. It makes the UI much more user-friendly.

0
NA
Answered on 28-01-2025

Make sure you also have a generic @ExceptionHandler(Exception.class) to catch any unexpected 500 errors so you don't leak internal stack traces to the public users.

KI 29-01-2025

Good point, Nancy. Leaking stack traces is a major security risk. Always log the full trace internally but only show a generic "Internal Error" message to the user.

Share your thoughts

Your email address will not be published. Required fields are marked (*)

Professional Counselling Session

Still have questions?
Schedule a free counselling session

Our experts are ready to help you with any questions about courses, admissions, or career paths. Get personalized guidance from industry professionals.

Request a Call Back

Search Online

We Accept

We Accept

Follow Us

"PMI®", "PMBOK®", "PMP®", "CAPM®" and "PMI-ACP®" are registered marks of the Project Management Institute, Inc. | "CSM", "CST" are Registered Trade Marks of The Scrum Alliance, USA. | COBIT® is a trademark of ISACA® registered in the United States and other countries.

Book Free Session