📝 Log Error Message in Java try/catch Blocks What Copilot Missed and What SonarQube Enforces? One thing I noticed is the piece of Java code generated by Copilot using Claude didn't meet SonarQube standard because it omitted logging inside catch statements when try/catch was used. Plus exception message is also required to be included in the log. Another thing I noticed is: 🔹 SonarQube in the pipeline enforces this rule strictly 🔹 Local SonarQube (or IDE plugins) does not Here're two use cases we can either log it or do not log it: ✔ Handle the exception → MUST LOG IT try { performAction(); } catch (IOException e) { logger.warn("perform action failed: {}", e.message()); fallback(); } ❌ Do not handle the exception → DO NOT LOG IT (Just rethrow it) try { performAction(); } catch (IOException e) { throw new MyIOException("Unable to perform action", e); // No log here } This prevents double logging. #Java #SpringBoot #SonarQube #CleanCode #SoftwareEngineering #Logging #GitHubCopilot #CodeQuality #BestPractices #DevOps #AI
Java Logging in Try/Catch Blocks: SonarQube Enforcement
More Relevant Posts
-
🚨 A Small File That Caused a Big Headache: classpath.txt Recently, I ran into an issue while working on a large Java project built with Maven. I was trying to start the application using an external dependency — the H2 database driver. Everything seemed correct. I followed the existing instructions carefully. I even executed a bash command to copy the H2 driver into the classes folder. But then… 💥 Error: Class not found (H2 driver) I got stuck. 🤔 What was missing? After digging around, I realized something important: 👉 The H2 driver was not declared in classpath.txt And surprisingly… this step wasn’t mentioned in the documentation. 📌 So, what is classpath.txt? In simple terms: 👉 classpath.txt is a file that tells Java where to find your classes and external libraries when the application runs. Think of it like a “map” 📍 If a library (like H2) is not listed there, Java simply cannot see it, even if the file physically exists in your project. ⚠️ Why copying files isn’t enough I assumed that copying the .jar into the classes folder would be enough. But Java doesn’t automatically scan everything in that folder. 👉 If it’s not in the classpath → it doesn’t exist (from Java’s perspective) ✅ The fix Once I added the H2 driver path into classpath.txt, everything worked immediately. 💡 Key takeaways If you import an external library without declaring it in pom.xml, make sure it is also added to classpath.txt so the compiler and runtime can detect it If you declare dependencies properly in pom.xml, Maven will handle the classpath for you — no need to manually add them to classpath.txt When you see a “Class not found” error, always double-check how your dependencies are being included 🚀 What I learned This bug helped me truly understand: How Java loads dependencies at runtime The role of classpath.txt in builds The right way to include external libraries Sometimes, the smallest files teach the biggest lessons. If you’ve ever been stuck on a “Class not found” error, you know the pain 😅 Hope this saves someone a few hours (or days). #Java #Maven #Debugging #SoftwareEngineering #Learning
To view or add a comment, sign in
-
🚀 Spring Annotation-Based Configuration (Beginner Friendly Guide) If you’re starting with Spring, understanding how the IOC container works is super important. Let’s break it down with a simple example 👇 👉 1. Main Class (Entry Point) import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) { // Step 1: Load Spring configuration file ApplicationContext container = new ClassPathXmlApplicationContext("applicationContext.xml"); // Step 2: IOC container is ready and beans are created automatically System.out.println("IOC Container Loaded Successfully ✅"); } } 👉 2. applicationContext.xml (Configuration File) <beans xmlns="https://lnkd.in/d858D-Nk" xmlns:xsi="https://lnkd.in/dNJZbNmc" xmlns:context="https://lnkd.in/dEDWzfEq" xsi:schemaLocation=" https://lnkd.in/d858D-Nk https://lnkd.in/dbit7sVK https://lnkd.in/dEDWzfEq https://lnkd.in/daN7U-FT"> <!-- Scan this package for annotations --> <context:component-scan base-package="org.annotationbasedconfiguration"/> </beans> 💡 What does this mean? ✔️ Spring reads the XML file ✔️ Scans the given package ✔️ Finds classes with annotations like: @Component @Service @Repository ✔️ Automatically creates objects (Beans) and manages them 🎯 Why use an Annotation-Based Approach? ✅ Less XML configuration ✅ Cleaner code ✅ Easy to manage ✅ Industry standard approach 👉 Simple Understanding: "Just add annotations in your class, and Spring will create & manage objects for you." #Java #SpringFramework #Beginners #BackendDevelopment #IoC #DependencyInjection #CodingJourney
To view or add a comment, sign in
-
A small Mockito habit that makes your tests cleaner : STOP mocking collections. I came across this recently and it clicked immediately. A lot of Java devs (myself included, at some point) write tests like this: ```java List<String> mockedList = mock(List.class); when(mockedList.size()).thenReturn(3); when(mockedList.get(0)).thenReturn("foo"); ``` It feels right. You're in a test, you're using Mockito, so you mock things. But this is actually an antipattern and here's why: → Collections are data, not dependencies. Mocks exist for things with external behavior like services, repositories, HTTP clients. A List has no I/O, no side effects, no non-determinism. It doesn't need to be mocked. → You end up writing more code than necessary. Every method your code touches size(), get(), isEmpty(), iterator() needs its own when() stub. A real ArrayList just works out of the box. → Your tests become fragile. If the code under test changes how it reads the list, your mock silently returns null instead of failing with a clear message. The fix is embarrassingly simple: ```java List<String> items = List.of("foo", "bar", "baz"); ``` Real data. No setup noise. The test tells you exactly what it's working with. Mockito even has a @DoNotMock annotation for exactly this reason to flag types that should never be mocked and steer you toward real instances instead. The rule of thumb: mock your collaborators, not your data. If it's a List, Map, or Set : just use the real thing. #Java #Mockito #UnitTesting #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
🚀 DTO Pattern in Spring Boot — Stop Exposing Your Entities! One of the most common mistakes junior Java developers make is returning JPA entities directly from REST controllers. Here's why DTOs will save your application architecture. What is a DTO? A Data Transfer Object is a simple POJO used to carry data between layers — decoupling your API contract from your database model. // ❌ BAD: Exposing entity directly @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return userRepository.findById(id).orElseThrow(); } // ✅ GOOD: Using DTO @GetMapping("/users/{id}") public UserResponseDto getUser(@PathVariable Long id) { User user = userRepository.findById(id).orElseThrow(); return mapper.toDto(user); } MapStruct makes this effortless — it generates mapping code at compile time with zero reflection overhead: @Mapper(componentModel = "spring") public interface UserMapper { UserResponseDto toDto(User user); User toEntity(CreateUserRequestDto dto); } Benefits: hide sensitive fields (passwords!), shape your API independently of DB schema, and reduce serialization issues with lazy-loaded relations. #Java #SpringBoot #BackendDevelopment #DTO #MapStruct #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐉𝐚𝐯𝐚 𝐒𝐭𝐚𝐫𝐭𝐬 𝐰𝐢𝐭𝐡 𝐒𝐭𝐫𝐨𝐧𝐠 𝐅𝐮𝐧𝐝𝐚𝐦𝐞𝐧𝐭𝐚𝐥𝐬 Most developers jump straight into frameworks… But the real edge lies in understanding the core of Java. Here’s a simplified breakdown of essential Java concepts every aspiring developer should know 👇 🔹 Java Basics • Difference between JDK, JRE & JVM • Platform independence & security features • Primitive vs Non-primitive data types • Control statements & exception types 🔹 Object-Oriented Programming (OOP) • Core pillars: Abstraction, Encapsulation, Inheritance, Polymorphism • Overloading vs Overriding • Abstract class vs Interface • Static vs Dynamic binding 🔹 Data Structures & Algorithms • Arrays vs Linked Lists • Hash Tables & HashSet working • BST time complexities • BFS vs DFS concepts • Dynamic Programming basics 🔹 Multithreading • Thread vs Process • Thread creation methods • Synchronization & Deadlocks • Runnable vs Thread class • Volatile keyword & scheduling 🔹 Exception Handling • Checked vs Unchecked exceptions • try-catch-finally usage • throw vs throws • Creating custom exceptions 💡 Key Insight: Java isn’t just about syntax—it’s about understanding how things work internally. Once your fundamentals are strong, frameworks like Spring and Hibernate become much easier to master. 📌 Whether you're a beginner or revising concepts, this roadmap can help you build a solid foundation. Consistency + Clarity = Growth in Tech. 👉🏻 follow Alisha Surabhi for more such content 👉🏻 PDF credit goes to the respected owners #Java #JavaProgramming #LearnJava #Programming #Coding #SoftwareDevelopment #OOP #DataStructures
To view or add a comment, sign in
-
🔁 Day 19 — Streams vs Loops: What Should Java Dev Choose? Choosing between Streams and Loops isn’t about syntax — it’s about clarity, performance, and scalability. Here’s how to decide like an architect: ✅ When to Use Loops (Traditional for-loop / enhanced for-loop) ✔ Better raw performance (no extra allocations) ✔ Ideal for hot code paths ✔ Easier to debug (breakpoints, step-through) ✔ Useful for complex control flow (break/continue/multiple conditions) 👉 If your logic is stateful or performance-critical → use loops. 🚀 When to Use Streams ✔ More expressive & declarative ✔ Perfect for transformations, filtering, mapping ✔ Parallel processing becomes trivial ✔ Cleaner code → fewer bugs ✔ Great for pipelined operations 👉 If readability > raw performance → use streams. ⚠️ When to Avoid Streams ❌ Complex branching logic ❌ Deeply nested operations ❌ Cases where debugging matters ❌ Tight loops in performance-sensitive sections 🔥 Architecture Takeaway Loops = Control + Speed Streams = Readability + Composability Parallel Streams = Only when data is large + workload is CPU-bound + fork-j join pool tuning is done Smart engineers know both. Architects know when to use which. #Microservices #Java #100DaysofJavaArchitecture #Streams #Loops
To view or add a comment, sign in
-
-
🚀 Build a 𝗛𝗶𝗴𝗵-𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲, 𝗧𝗵𝗿𝗲𝗮𝗱-𝗦𝗮𝗳𝗲 Java Logging Framework I designed and implemented a 𝗖𝘂𝘀𝘁𝗼𝗺 𝗝𝗮𝘃𝗮 𝗟𝗼𝗴𝗴𝗶𝗻𝗴 𝗙𝗿𝗮𝗺𝗲𝘄𝗼𝗿𝗸 from scratch, focusing on performance, thread safety, and reusability across multiple modules instead of relying on existing logging libraries. The objective was to build a modular, extensible, and thread-safe logging utility that can be reused across Spring Boot applications. 🏗️ Architecture Highlights • 𝗙𝗮𝗰𝘁𝗼𝗿𝘆 𝗣𝗮𝘁𝘁𝗲𝗿𝗻 → Centralized logger creation using LoggerFactory • 𝗦𝗶𝗻𝗴𝗹𝗲𝘁𝗼𝗻 𝗽𝗲𝗿 𝗖𝗹𝗮𝘀𝘀→ Managed using ConcurrentHashMap<String, CustomLogger> • Thread-safe initialization using computeIfAbsent() • 𝗦𝘁𝗿𝗮𝘁𝗲𝗴𝘆 𝗣𝗮𝘁𝘁𝗲𝗿𝗻 → Separate Formatter, Writer, and Level handling • 𝗣𝗮𝗰𝗸𝗮𝗴𝗲𝗱 𝗮𝘀 𝗿𝗲𝘂𝘀𝗮𝗯𝗹𝗲 𝗝𝗔𝗥 → Plug-and-play across Controller / Service / Repository layers ⚡ Key Technical Points • 𝗟𝗼𝗰𝗸-𝗳𝗿𝗲𝗲 𝗰𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝗰𝘆 𝘂𝘀𝗶𝗻𝗴 𝗖𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝘁𝗛𝗮𝘀𝗵𝗠𝗮𝗽. • One logger instance per class (singleton strategy) • Multi-module reusable logging library • Clean separation of concerns following SOLID principles • Designed for safe usage in multi-threaded environments 🔄 Flow Application Layer → LoggerFactory → ConcurrentHashMap Cache → CustomLogger → Formatter / Level / Writer → Console Output The framework is packaged as a reusable library and integrated into a Spring Boot project to simulate real-world multi-layer usage. GitHub: https://lnkd.in/gKpGZrCy This project focuses on practical low-level design, concurrency, and reusable library architecture. #Java #SystemDesign #LowLevelDesign #Concurrency #SpringBoot #DesignPatterns #BackendDevelopment #SoftwareArchitecture
To view or add a comment, sign in
-
-
Ever spent hours debugging a production issue only to find... absolutely nothing in the logs? 🕵️♂️ I recently went down a rabbit hole investigating why critical database failures were vanishing in our asynchronous code paths. I checked Loki, container logs, and stderr—but the system was dead silent. It turns out Java's asynchronous APIs can be a "silent trap." If you're using ThreadPoolExecutor or ScheduledThreadPoolExecutor, unhandled exceptions are often captured and stored within a Future object. If you don't explicitly call .get(), those exceptions may never see the light of day. The Solution? I implemented a LoggingRunnable wrapper and specialized LoggingThreadPools using the Delegate Pattern. This allows us to: ✅ Automatically intercept tasks. ✅ Ensure every Throwable is logged before it vanishes. ✅ Keep the original business logic clean and decoupled from logging concerns. No more "gobbled" exceptions or flying blind in production. Read the full technical deep dive on my blog: https://lnkd.in/gfmJwkMw #Java #SoftwareEngineering #Debugging #Backend #CleanCode #Concurrency #Programming #JavaDevelopment #eGluTech
To view or add a comment, sign in
-
Built an HTTP server from scratch in Java. No frameworks. No Netty. No Spring Boot. Just raw sockets, manual byte parsing, and a thread pool wired from the ground up. The goal was never to reinvent the wheel. It was to understand what the wheel is actually made of. What was built: → TCP socket listener handing connections to a fixed thread pool of 500 workers → HTTP/1.1 parser written byte-by-byte - request line, headers, body (JSON + form-urlencoded) → Router handling HEAD, GET and POST with static file serving and query param injection → Structured error responses for 400, 404, 500, 501, and 505 → WebRootHandler with path traversal protection → Full JUnit test suite, Maven build, SLF4J logging, and a Dockerized deployment What it reinforced: Networking - HTTP is just bytes on a wire. The kernel speaks TCP, not HTTP. The parser is what gives those bytes meaning. Operating systems - the boundary between user space and kernel space stopped being abstract. accept(), read(), write() are syscalls. Everything else lives in the JVM. Concurrency - 500 threads sharing a single handler. Statelessness stops being a design preference and becomes a correctness requirement. Docker - the container wraps the JVM, not the kernel. Syscalls go to the host kernel. There is no container kernel. Building something from scratch is one of the most honest ways to learn. Every assumption gets tested, every abstraction gets earned. A recommendation from Kashif Sohail turned into weeks of going deep on networking, OS internals, and concurrency. Grateful for that push. GitHub repo :https://lnkd.in/dxxjXxpt #Java #Networking #OperatingSystems #Backend #SystemsEngineering #Docker #OpenSource
To view or add a comment, sign in
-
-
🚀 Spring Framework 🌱 | Day 5 How IOC Works Internally (Step by Step) 1️⃣ Configuration Loading Spring reads configuration (Annotations / XML / Java Config like @Component, @Bean). 2️⃣ Bean Definition Creation Spring identifies classes and creates bean definitions (metadata about objects). 3️⃣ IOC Container Initialization IOC container (like ApplicationContext) starts and prepares to manage beans. 4️⃣ Object Creation (Bean Instantiation) Spring creates objects (beans) instead of you using new. 5️⃣ Dependency Injection (DI) Spring injects required dependencies (@Autowired, constructor, setter). 6️⃣ Bean Initialization Spring calls init methods (@PostConstruct or custom init). 7️⃣ Bean Ready to Use Now the object is fully ready and managed by Spring. 8️⃣ Bean Lifecycle Management Spring manages the entire lifecycle (creation → usage → destruction). 9️⃣ Bean Destruction When the application stops, Spring calls destroy methods (@PreDestroy). ✨ IOC = Less effort, more control by Spring! #Java #SpringFramework #BackendDevelopment #Coding #InterviewPreparation
To view or add a comment, sign in
-
More from this author
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