How do you handle exceptions globally in Spring Boot using @ControllerAdvice? स्प्रिंग बूट में @ControllerAdvice का उपयोग करके एक्सेप्शन को ग्लोबली कैसे हैंडल करें?
@ControllerAdvice defines a global exception-handling component that applies across all controllers, keeping error-handling logic out of individual controller methods. Inside it, methods annotated with @ExceptionHandler(SomeException.class) catch a specific exception type and return a consistent error response.
Combined with a ResponseEntity, this pattern centralizes error formatting — mapping exceptions like ResourceNotFoundException to 404, validation errors to 400, and unexpected exceptions to 500 — so every endpoint returns errors in the same shape.
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(ex.getMessage()));
}
}@ControllerAdvice एक ग्लोबल एक्सेप्शन-हैंडलिंग कंपोनेंट डिफाइन करता है जो सभी कंट्रोलर्स पर लागू होता है, जिससे एरर-हैंडलिंग लॉजिक अलग-अलग कंट्रोलर मेथड्स से बाहर रहता है। इसके अंदर, @ExceptionHandler(SomeException.class) से एनोटेट मेथड्स एक विशिष्ट एक्सेप्शन टाइप को पकड़ते हैं और एक सुसंगत एरर रिस्पॉन्स रिटर्न करते हैं।
ResponseEntity के साथ मिलाकर, यह पैटर्न एरर फॉर्मेटिंग को केंद्रीकृत करता है — जैसे ResourceNotFoundException को 404 से, वैलिडेशन एरर को 400 से मैप करना — जिससे हर एंडपॉइंट एक ही स्वरूप में एरर रिटर्न करता है।
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErrorResponse(ex.getMessage()));
}
}Was this answer clear?