🚀 Day 24/100: Spring Boot From Zero to Production Topic: Global Exception Handling with @ControllerAdvice The Problem: Spring Boot's default error response? Not great for real APIs. It returns vague, inconsistent JSON that tells your frontend... nothing useful. The Fix: One Class to Rule Them All @ControllerAdvice acts as a global interceptor across all your controllers. Pair it with @ExceptionHandler and you get clean, consistent errors everywhere. -> One class handles exceptions from every controller -> Spring automatically picks the most specific handler -> No try-catch clutter inside your business logic Clean. No noise. The exception carries the message, your handler just shapes the response. Same status code. But now the client actually knows what went wrong. 3 key takeaways: 1. Use @RestControllerAdvice -> it's @ControllerAdvice + @ResponseBody in one shot 2. Build a custom exception hierarchy -> one base class, one handler, infinite exceptions 3. Never expose stack traces or SQL errors in your 500 response -> log them, don't leak them #Java #SpringBoot #ExceptionHandling #100DaysOfCode #Backend
Global Exception Handling in Spring Boot with @ControllerAdvice
More Relevant Posts
-
🚀 Day 18/100: Spring Boot From Zero to Production Topic: Auto-Configuration 💡 What is Auto-Configuration? One of the most powerful features in Spring Boot Turns hours of setup into minutes Eliminates heavy XML configs and manual bean wiring ⏳ Before Auto-Configuration Manually define multiple beans Write hundreds of lines of XML Configure everything yourself → painful ⚙️ What Happens Now? Your @SpringBootApplication kicks things off Spring Boot scans the classpath Looks for dependencies like: spring-webmvc spring-data-jpa 👉 Presence/absence of JARs = signals 🧠 Behind the Scenes Reads a special file: META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports Contains hundreds of auto-config classes Each uses conditions like: @ConditionalOnClass @ConditionalOnMissingBean 👉 Result: Beans get configured automatically 🌐 Simple Example Add: spring-boot-starter-web Spring Boot assumes: You need a web app So it adds an embedded server (Tomcat) automatically 🛠️ Can You Override It? YES You can: Define your own beans Override defaults Disable auto-config if needed Auto-configuration isn’t magic. It’s just smart defaults + conditional logic working for you #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #Backend
To view or add a comment, sign in
-
-
Most backend APIs are badly designed… and routing is usually the reason. I used to think routing was just: “URL → function” But it’s much deeper than that. Here’s what I learned 👇 • Method = what you want to do (GET, POST…) • Route = where you want to do it (/users, /books) • Together → form a unique key that decides backend behavior Types of routing that actually matter: • Static → fixed endpoints • Dynamic → /users/:id • Query params → filtering, pagination • Nested routes → relationships between resources • Versioning → avoid breaking production APIs • Catch-all → clean error handling 💡 Biggest realization: 👉 Good routing = clean APIs = scalable systems Bad routing = messy logic + hard-to-maintain backend I’ve put together clean notes in a PDF 👇 #BackendEngineering #SystemDesign #APIDesign #Java #SpringBoot
To view or add a comment, sign in
-
🚀 Day 19/100: Spring Boot From Zero to Production Topic: Disabling Auto Configuration Quick Recap previously we covered Auto Configuration in Spring Boot. (Link to that post in the comments 👇) The Problem: Auto Configuration is magical. But magic shouldn't cage you. Sometimes you need to go beyond the defaults. Sometimes a specific auto config just gets in your way. So the question is.... does Spring Boot let you opt out? Absolutely. And it's dead simple. ✅ How to Disable Auto Configuration: Just add an exclude to your @SpringBootApplication annotation: @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) public class MunasibApplication{ public static void main(String[] args) { SpringApplication.run(MyApp.class, args); } } That's it. One line. No database auto-wiring. Done. Not Just DataSource You're not limited to one config. Exclude multiple auto configurations at once Works with any AutoConfiguration class Spring Boot ships @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, SecurityAutoConfiguration.class }) Alternative: Use application.properties Don't want to touch your code? spring.autoconfigure.exclude=\org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration Same result. Zero code change. 🎯 Why This Matters Spring Boot gives you sensible defaults. But it never forces them on you. That's what makes it a great framework, not just smart, but flexible. #Java #SpringBoot #SoftwareDevelopment #100DaysOfCode #AutoConfiguration
To view or add a comment, sign in
-
-
🚀 Spring Framework 🌱 | Day 17 Exception Handling in Spring Boot (Real Project Approach) In many projects, I’ve seen controllers filled with try-catch blocks. It works… but it quickly becomes messy and hard to maintain. A better approach in Spring Boot is: 👉 Centralized Exception Handling using @ControllerAdvice 💡 It’s important to follow these best practices in real projects. 1️⃣ Create a Global Exception Handler - Use @ControllerAdvice - Handle all exceptions in one place 2️⃣ Define Custom Exceptions - Example: ResourceNotFoundException, BusinessException - Helps in better clarity instead of generic Exception 3️⃣ Standard API Error Response Instead of random messages, always return structured response: { "timestamp": "...", "status": 404, "error": "Not Found", "message": "User not found", "path": "/users/10" } 4️⃣ Map Exceptions Properly - 400 → Bad Request (validation issues) - 404 → Resource not found - 500 → Unexpected errors 5️⃣ Avoid exposing internal details - Never return stack trace in API response (security risk) 🔥 Why this matters? ✔ Cleaner Controllers (no repetitive try-catch) ✔ Consistent API responses ✔ Easy debugging & logging ✔ Production-ready design ⚡ Pro Tip: Combine @ControllerAdvice with proper logging (SLF4J) and monitoring tools for better debugging in production. #SpringBoot #Java #BackendDevelopment #CleanCode #Microservices #SoftwareEngineering
To view or add a comment, sign in
-
-
Stop labeling your Spring Beans randomly! 🛑 I see many projects where @Component, @Service, and @Repository are used interchangeably. They all register a Bean in the context, so they are the same, right? Not exactly. Using the right stereotype is about Communication and Semantics. 🔹 @Service: Clearly states: "This is where the business logic lives." It's your domain's heart. 🔹 @Repository: Signals: "I talk to the database." Spring provides an extra layer of magic here: it automatically translates platform-specific exceptions (like SQLException) into Data Access Exceptions. 🔹 @Component: The generic catch-all. Use it for utility classes or anything that doesn't fit the service/repository pattern. Tip: Using the correct label makes your code readable for the next dev. It tells a story about what each class is responsible for before they even read a single line of implementation. How strict is your team with stereotyping their Spring components? Let’s talk below! 👇 #Java #SpringBoot #SoftwareArchitecture #CleanCode #Backend #SpringFramework #CleanDesign
To view or add a comment, sign in
-
-
What actually happens when you hit a Spring Boot API? In my previous post, I explained how Spring Boot works internally. Now let’s go one level deeper 👇 What happens when a request hits your application? --- Let’s say you call: 👉 GET /users Here’s the flow behind the scenes: 1️⃣ Request hits embedded server (Tomcat) Spring Boot runs on an embedded server that receives the request. --- 2️⃣ DispatcherServlet takes control This is the core of Spring MVC. It acts like a traffic controller. --- 3️⃣ Handler Mapping DispatcherServlet finds the correct controller method for the request. --- 4️⃣ Controller Execution Your @RestController handles the request → Calls service layer → Fetches data from DB --- 5️⃣ Response conversion Spring converts the response into JSON using Jackson. --- 6️⃣ Response sent back Finally, the client receives the response. --- Why this matters? Understanding this flow helps in: ✔ Debugging production issues ✔ Writing better APIs ✔ Improving performance Spring Boot hides complexity… But knowing what’s inside makes you a better backend developer. More deep dives coming #Java #SpringBoot #BackendDevelopment #Microservices
To view or add a comment, sign in
-
As developers, we all say *“async = separate thread”*… but when I went deeper during development, a few real questions hit me 👇 Can I actually **see which thread is running my async task?** Yes — using `Thread.currentThread().getName()` you can log and observe it. But then the bigger question… 👉 **How many threads are actually created?** 👉 Is it always a new thread per task? 👉 Or are threads reused? I came across a post saying **“by default 8 threads are used”** — but is that really true in all cases? From what I understand so far: * It depends on the **thread pool configuration** * Frameworks like Spring Boot often use executors (not raw thread creation) * Threads are usually **reused**, not created every time But I want to hear from real-world experience 👇 💬 How does async actually behave in production systems? 💬 What decides the number of threads? 💬 Any pitfalls you’ve seen while working with async? Let’s learn from each other 🚀
To view or add a comment, sign in
-
One thing I’ve learned building backend systems: Audit logging always starts as a “simple requirement” …and ends up being a complex subsystem. - Who changed what? - When did it happen? - Can we query it efficiently? Most teams either: 1. Over-engineer it 2. Or build something they regret later So I decided to build it properly once. Introducing nerv-audit (now on Maven Central): A Spring Boot audit framework powered by Hibernate Envers, with: - Clean architecture - Queryable audit history - Production-ready design If you're building serious systems, this is something you’ll eventually need. Full write-up here: https://lnkd.in/g2sv9dsM Curious how others are handling audit trails in their systems 👇 #SpringBoot #Java #SoftwareEngineering #Backend #OpenSource
To view or add a comment, sign in
-
#Post6 In the previous posts, we built basic REST APIs step by step. But what happens when something goes wrong? 🤔 Example: User not found Invalid input Server error 👉 By default, Spring Boot returns a generic error response. But in real applications, we need proper and meaningful error handling. That’s where Exception Handling comes in 🔥 Instead of handling exceptions in every method, Spring provides a better approach using @ControllerAdvice 👉 It allows us to handle exceptions globally Example: @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public String handleException(Exception ex) { return ex.getMessage(); } } 💡 Why use this? • Centralized error handling • Cleaner controller code • Better API response Key takeaway: Use global exception handling to manage errors in a clean and scalable way 🚀 In the next post, we will create custom exceptions for better control 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
To view or add a comment, sign in
-
Spring Boot Magic ✨ — Pagination Fetching thousands of records in one API call? That’s a performance nightmare waiting to happen 😅 👉 That’s where Pagination comes in. Pagination helps you load data in small chunks (pages) instead of everything at once. 💡 Why it matters? ✔ Improves performance ✔ Reduces memory usage ✔ Faster APIs ✔ Better user experience ⚙️ How it works in Spring Boot? Use Pageable to request data Return Page<T> from repository/service Control page, size, and sorting easily Example: /api/users?page=0&size=10&sortBy=id That’s it… clean, scalable, and production-ready 🚀 If you're building APIs and not using pagination, you're putting unnecessary load on your system. #SpringBoot #Java #Pagination #BackendDevelopment #APIDesign #CleanCode
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development