#Post7 In the previous post, we saw how to handle exceptions globally using @ControllerAdvice. Now let’s take it one step further 👇 How do we handle specific errors properly? That’s where Custom Exceptions come in 🔥 Instead of using generic exceptions, we can create our own exception based on the use case. Example: public class UserNotFoundException extends RuntimeException { public UserNotFoundException(String message) { super(message); } } 👉 Now we can throw this exception when user is not found Example usage: if(user == null){ throw new UserNotFoundException("User not found"); } 💡 Why use Custom Exceptions? • Better error clarity • Easy debugging • More control over API responses Key takeaway: Use custom exceptions to make your API errors more meaningful and structured 👍 In the next post, we will understand validation using @Valid 🔥 #Java #SpringBoot #BackendDevelopment #RESTAPI #LearnInPublic
Girish kolhe’s Post
More Relevant Posts
-
Have you ever debugged a production issue where logs show the same error everywhere… but you still can’t figure out what actually failed? I used to make this mistake a lot — catch exception → log error → throw again Service logs Repository logs Controller logs Same exception 3–4 times. Just noise. Then I changed one simple thing: don’t log where you’re just throwing the exception. Now I follow this: Service/Repository → just throw or wrap the exception Log only once at the boundary (API / consumer) Always add context We often don’t pay much attention to logging, but it plays a crucial role when debugging a system. You need clarity on where to log, what to log, and where not to. Now instead of messy logs, I get one clear error log with full context. Debugging feels less like guessing and more like tracing a story. Less logs. Better logs. That’s the real strategy. #BackendDevelopment #Microservices #SystemDesign #Java #SpringBoot #Logging #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
🚨 Why I stopped using field injection in Spring Boot I used to write this: @Autowired private UserService userService; Looks clean… but caused real issues. ❌ Problems: * Hard to test * Hidden dependencies * NullPointer risks in edge cases ✅ Now I always use constructor injection: public UserController(UserService userService) { this.userService = userService; } 💥 Real benefit: While writing unit tests, I realized I could mock dependencies easily without Spring context. 💡 Takeaway: Field injection is convenient. Constructor injection is production-safe. Small change. Big impact. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #Microservices #RESTAPI #SystemDesign #DeveloperLife #100DaysOfCode
To view or add a comment, sign in
-
🧠 After learning the Spring Bean Lifecycle, I explored another powerful concept today 👀 Singleton vs Prototype Bean Scope in Spring Boot 🚀 The default scope in Spring is singleton 👇 ✅ Only one object instance is created ✅ Shared across the whole application ✅ Best for services, repositories, controllers Then comes prototype 👇 🔁 A new object is created every time it is requested This makes it useful for: ✅ temporary objects ✅ stateful helpers ✅ per-request custom processing 💡 My takeaway: Bean scope directly changes how Spring manages memory and object reuse. Small annotations can completely change runtime behavior ⚡ #Java #SpringBoot #BeanScope #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
Last weekend I’ve been studying more about error handling and I watched a great video from Dan Vega — an interesting view on how to implement error handling and retries. 🚀 I pushed a small demo repo that captures those ideas using Spring Boot’s new RestClient and a clean error-handling pattern: 🔁 Retry transient failures with @Retryable (exponential backoff). 🧭 Centralize response-to-exception mapping via RestClient’s defaultStatusHandler (ApiException, NotFoundException). 🛡️ Serve consistent ProblemDetail (RFC 7807) responses from a GlobalExceptionHandler for clearer API errors. 🧪 Uses https://httpbin.org/ to simulate status codes and unstable endpoints for deterministic testing. Why this is valuable: - Increases reliability by handling transient errors consistently. - Keeps controllers and business logic clean — the client layer interprets remote errors. - Improves client experience with predictable, machine-readable error payloads. Inspired by Dan Vega’s walkthroughs — credit to him for the patterns and clarity. 🙏 Feel curious how that I did it, check the repo to see the config, examples, and how to adapt this pattern: https://lnkd.in/dEe3HNKr #SpringBoot #Java #Resilience #ErrorHandling #RestClient #Microservices
To view or add a comment, sign in
-
When updating data in a Spring Boot API, standard validation can be too restrictive, often requiring all fields to be sent even for minor changes. A more flexible solution is to use @Validated with validation groups. This approach allows you to define separate sets of rules. For example, you can have a "create" group that requires all fields to be present, and a "default" group that only checks the format of fields that are actually provided in the request. In your controller, you then apply the appropriate rule set: the strict rules for creating new items and the flexible rules for updating them. This allows your API to handle both full and partial updates cleanly while reusing the same data object, resulting in more efficient code. #SpringBoot #Java #API #Validation #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚨 Poor logging = nightmare in production I learned this the hard way. 💥 Issue: Bug reported → logs useless Why? - No context - No request IDs - Random print statements ✅ Fix: - Structured logging - Added correlation IDs - Used proper log levels 💡 Takeaway: Logs are your only visibility in production. Write logs like you’ll debug them at 2 AM. #Java #SpringBoot #BackendDevelopment #SoftwareEngineering #Microservices #JPA #RESTAPI #DeveloperLife #CareerGrowth
To view or add a comment, sign in
-
Recently, I shared how reducing multiple API calls improved performance. This time, I ran into a different issue. My API response looked fine… until I saw the payload size. While working on a feature, everything was working as expected. But the response felt heavier than it should be. After checking, I realized I was returning full objects, even when only a few fields were actually needed. So for a single request, I was sending a large JSON response unnecessarily. I made a small change: Instead of returning everything, I started sending only what the client actually needs. Used DTOs to control the response and removed unused fields. That made a clear difference: - Smaller payload - Faster response - Cleaner API Last time, the issue was too many API calls. This time, it was too much data in one call. (Check the previous post: https://lnkd.in/gxSKFVbk) Sometimes performance issues are not about complex fixes… they’re about reducing unnecessary work. #Java #BackendDevelopment #SpringBoot #API #Performance #LearningInPublic
To view or add a comment, sign in
-
-
Healthy services can still create a broken system. That lesson took me longer to learn than it should have. Early on, I used to judge systems service by service: Is inventory up? Is pricing up? Is payment up? But production does not care whether each box is green in isolation. It cares about the full request path. That changed how I look at failures, tracing, retries, and resilience. A lot of systems are not failing at the component level. They are failing at the interaction level. What taught you that lesson? #Java #SpringBoot #DistributedSystems #Microservices #BackendEngineering
To view or add a comment, sign in
-
Cache bugs are often not bugs at all. They are contracts we forgot to read. This tutorial walks through Quarkus cache failure semantics with a small pricing service: - `@CacheResult` on `Uni` - resolved-value caching - success-only `@CacheInvalidateAll` - stale data after failed methods with surviving side effects - forced invalidation with `CacheManager` The practical question is simple: when is stale data better than a cache miss, and when is it dangerous? https://lnkd.in/dShFxDDQ #Quarkus #Java #Caching #ReactiveJava
To view or add a comment, sign in
-
-
I was lost in the Java Stream API jungle. 🌿 Too many methods. No structure. Pure confusion. Then one thing clicked — it's just a pipeline: 👉 Source → Intermediate(s) → Terminal So I mapped out every widely used operation by stage in one visual. Feel free to bookmark it for the next time a Stream method trips you up. 📌 Chart generated with Claude by Anthropic. #Java #Java8 #Java21 #StreamAPI #JavaDeveloper #CleanCode #LearningInPublic
To view or add a comment, sign in
-
Explore related topics
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