CodexBloom - Programming Q&A Platform

Spring MVC: How to Properly Handle Custom Exceptions with @ControllerAdvice and Return a Custom JSON Response

πŸ‘€ Views: 86 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
spring-mvc exception-handling controlleradvice Java

I'm having trouble with I'm currently working on a Spring MVC application (version 5.3.10) and I want to implement a global exception handling mechanism using `@ControllerAdvice`... I've created a custom exception called `ResourceNotFoundException`. However, when this exception is thrown, I want to return a custom JSON response with specific fields, but I'm running into issues getting the response format just right. Here’s the code for my custom exception: ```java public class ResourceNotFoundException extends RuntimeException { public ResourceNotFoundException(String message) { super(message); } } ``` I've set up a `@ControllerAdvice` like this: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex) { Map<String, Object> response = new HashMap<>(); response.put("error", "Resource Not Found"); response.put("message", ex.getMessage()); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } } ``` When I throw the exception in my controller like this: ```java @GetMapping("/resources/{id}") public ResponseEntity<Resource> getResource(@PathVariable String id) { Resource resource = resourceService.findById(id); if (resource == null) { throw new ResourceNotFoundException("Resource with ID " + id + " not found"); } return ResponseEntity.ok(resource); } ``` I expect to see a JSON response formatted like this: ```json { "error": "Resource Not Found", "message": "Resource with ID 123 not found" } ``` However, I'm receiving a plain error message without any JSON formatting. The response is just the default error page from Spring. I've double-checked that my controller and the exception handler methods are being hit, but the JSON response isn't being returned as expected. I've also ensured that Jackson is on the classpath. What am I missing? Is there a specific configuration I need to set to enable this behavior, or is there perhaps a more appropriate way to structure my `@ControllerAdvice`? Any help would be greatly appreciated! Is this even possible? I'm working on a REST API that needs to handle this. Any help would be greatly appreciated! I recently upgraded to Java 3.11. I'd love to hear your thoughts on this.