Global Exception Handling in Spring Boot

🚀 Tired of writing try-catch in every controller? There’s a better way 👇 --- 👉 Problem: @RestController public class UserController { @GetMapping("/user/{id}") public User getUser(@PathVariable int id) { try { return userService.getUser(id); } catch (Exception e) { return null; // ❌ bad practice } } } ❌ Issues: - Repeated code - Messy controllers - Hard to maintain --- ✅ Solution → Global Exception Handling Use @ControllerAdvice + @ExceptionHandler --- 💡 Example: @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<String> handleException(Exception ex) { return new ResponseEntity<>("Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR); } } --- 👉 Now, any exception in your app: ✔ Automatically handled ✔ Clean response returned ✔ No try-catch in controllers --- 🔥 Handle specific exceptions: @ExceptionHandler(UserNotFoundException.class) public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) { return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND); } --- ⚡ Real-world impact: Without this: ❌ Inconsistent error responses ❌ Debugging becomes hard With this: ✅ Clean API responses ✅ Centralized error handling ✅ Production-ready backend --- 📌 Key Takeaway: Don’t handle exceptions everywhere… Handle them in ONE place. --- Follow for more real backend learnings 🚀 #SpringBoot #Java #BackendDevelopment #CleanCode #SoftwareEngineer

  • graphical user interface

To view or add a comment, sign in

Explore content categories