<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shivi Bhardwaj on Medium]]></title>
        <description><![CDATA[Stories by Shivi Bhardwaj on Medium]]></description>
        <link>https://medium.com/@shivibh?source=rss-2660c028d341------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k8YTvk-U5ACqtlRZ.jpg</url>
            <title>Stories by Shivi Bhardwaj on Medium</title>
            <link>https://medium.com/@shivibh?source=rss-2660c028d341------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 23:11:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivibh/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[An attempt to build MCP Server for UK Open Banking: A Technical Deep Dive]]></title>
            <link>https://medium.com/@shivibh/an-attempt-to-build-mcp-server-for-uk-open-banking-a-technical-deep-dive-a3f439a4b9b6?source=rss-2660c028d341------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3f439a4b9b6</guid>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[open-banking]]></category>
            <category><![CDATA[conversational-ai]]></category>
            <dc:creator><![CDATA[Shivi Bhardwaj]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 14:14:48 GMT</pubDate>
            <atom:updated>2025-10-25T14:14:48.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bridging AI Assistants with Financial APIs Using Model Context Protocol</h3><p>The convergence of Large Language Models (LLMs) and financial APIs represents one of the most compelling opportunities in fintech today. This article explores how the Model Context Protocol (MCP) enables seamless integration between AI assistants like Claude and UK Open Banking APIs, demonstrating an implementation in Java 21 and Spring Boot 3.</p><h3>Part I: Understanding the Model Context Protocol</h3><h3>What is MCP?</h3><p>The Model Context Protocol is Anthropic’s open standard for connecting AI assistants to external data sources and tools. Unlike traditional REST APIs that require explicit endpoint management, MCP provides a declarative interface where tools are discovered dynamically and invoked through natural language.</p><pre>┌─────────────┐    JSON-RPC 2.0    ┌─────────────┐<br>│   Claude    │ ◄─────────────────►│ MCP Server  │<br>│  Assistant  │    over stdio      │             │<br>└─────────────┘                    └──────┬──────┘<br>                                          │<br>                                    ┌─────▼──────┐<br>                                    │  External  │<br>                                    │    APIs    │<br>                                    └────────────┘</pre><h3>Key MCP Concepts</h3><ol><li><strong>Tools:</strong> Function definitions exposed to the LLM with JSON schemas</li></ol><pre>{<br>  &quot;name&quot;: &quot;get_accounts&quot;,<br>  &quot;description&quot;: &quot;Retrieve all bank accounts&quot;,<br>  &quot;inputSchema&quot;: {<br>    &quot;type&quot;: &quot;object&quot;,<br>    &quot;properties&quot;: {<br>      &quot;access_token&quot;: {&quot;type&quot;: &quot;string&quot;}<br>    },<br>    &quot;required&quot;: [&quot;access_token&quot;]<br>  }<br>}</pre><p><strong>2. Resources:</strong> Static or dynamic content (files, databases, APIs)</p><p><strong>3. Prompts:</strong> Pre-configured interaction templates</p><p><strong>4. JSON-RPC 2.0:</strong> Request/response protocol over stdio</p><pre>{<br>  &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>  &quot;method&quot;: &quot;tools/call&quot;,<br>  &quot;params&quot;: {<br>    &quot;name&quot;: &quot;get_accounts&quot;,<br>    &quot;arguments&quot;: {&quot;access_token&quot;: &quot;...&quot;}<br>  },<br>  &quot;id&quot;: 1<br>}</pre><h3>Why MCP Matters for Enterprise</h3><p>Traditional API integration requires:</p><ul><li>Explicit client libraries</li><li>Complex authentication flows</li><li>Manual request construction</li><li>Response parsing and error handling</li></ul><p>MCP enables:</p><ul><li><strong>Natural language invocation:</strong> “Show me my account balances”</li><li><strong>Dynamic discovery:</strong> Tools auto-registered with the LLM</li><li><strong>Unified interface:</strong> Single protocol for multiple backends</li><li><strong>Context preservation:</strong> Conversational state management</li></ul><h3>Part II: The Value Proposition for UK Open Banking</h3><h3>Current State of Open Banking Integration</h3><p>UK Open Banking APIs, while standardized, present integration challenges:</p><ol><li><strong>OAuth Complexity:</strong> Multi-step authorization flows</li><li><strong>API Fragmentation:</strong> 9+ CMA9 banks with subtle differences</li><li><strong>Developer Friction:</strong> High barrier to entry for consumers</li><li><strong>Limited Accessibility:</strong> Technical knowledge required</li></ol><h3>MCP as an Enabler</h3><p>An MCP server transforms Open Banking from a developer tool to a conversational interface:</p><p>Traditional Approach:</p><pre>// Manual API orchestration<br>OAuthToken token = getToken();<br>AccountsResponse accounts = client.getAccounts(token);<br>for (Account account : accounts.getData().getAccounts()) {<br>    BalanceResponse balance = client.getBalance(account.getId(), token);<br>    TransactionResponse txns = client.getTransactions(<br>        account.getId(), fromDate, toDate, token);<br>    // Manual aggregation and analysis<br>}</pre><p>MCP-Enabled Approach:</p><pre>User: &quot;Analyze my spending on groceries over the last 3 months&quot;<br>Claude: [Automatically orchestrates multiple API calls]<br>        [Aggregates data]<br>        [Performs analysis]<br>        [Presents insights]</pre><h3>Business Value</h3><p><strong>For Consumers:</strong></p><ul><li><strong>Zero learning curve:</strong> Natural language replaces API documentation</li><li><strong>Proactive insights:</strong> AI-driven financial analysis</li><li><strong>Multi-bank aggregation:</strong> Single interface across institutions</li></ul><p><strong>For Financial Institutions:</strong></p><ul><li><strong>Increased API adoption:</strong> Lower barrier to Open Banking usage</li><li><strong>Enhanced customer engagement:</strong> Conversational banking experiences</li><li><strong>Competitive differentiation:</strong> AI-first banking interfaces</li></ul><p><strong>For Developers:</strong></p><ul><li><strong>Rapid prototyping:</strong> MCP servers in hours, not weeks</li><li><strong>Standardization:</strong> Single codebase for multiple banks</li><li><strong>Maintainability:</strong> Declarative tool definitions vs. imperative code</li></ul><h3>Real-World Use Cases</h3><ol><li><strong>Personal Finance Management:</strong> “How much did I spend on dining out last month vs. this month?”</li><li><strong>Automated Reconciliation:</strong> “Check if all my expected salary payments arrived this quarter”</li><li><strong>Smart Payments:</strong> “Pay my utility bills that are due this week”</li><li><strong>Financial Planning:</strong> “Am I on track to save £10k by year-end based on current spending?”</li><li><strong>Fraud Detection:</strong> “Were there any unusual transactions in my account yesterday?”</li></ol><h3>Part III: Implementation Guide</h3><h3>Component Overview</h3><p>Our implementation consists of three components:</p><ol><li><strong>Spring Boot MCP Server</strong> (Port 8080, HTTP)</li><li><strong>Stdio Bridge</strong> (Java, translates stdio ↔ HTTP)</li><li><strong>Claude Desktop</strong> (MCP client)</li></ol><h3>Code Reference</h3><p>The complete implementation is available on GitHub:</p><p><strong>Repository:</strong> <a href="https://github.com/Frictionlessdev/openbanking-mcp-server">github.com/Frictionlessdev/openbanking-mcp-server</a></p><p><strong>Contents:</strong></p><ul><li>Full Spring Boot 3 MCP server implementation</li><li>Stdio bridge for Claude Desktop integration</li></ul><h3>Conclusion</h3><p>The Model Context Protocol represents a paradigm shift in how we integrate AI with enterprise systems. By building an MCP server for UK Open Banking, we’ve demonstrated:</p><ol><li><strong>Technical Feasibility:</strong> Production-grade implementation in ~1000 LOC</li><li><strong>User Experience:</strong> Natural language replacing complex API interactions</li><li><strong>Business Value:</strong> Dramatically lower barriers to Open Banking adoption</li><li><strong>Extensibility:</strong> Foundation for advanced financial AI applications</li></ol><p>As LLMs become increasingly capable, MCP will serve as the critical bridge between conversational interfaces and the structured world of financial APIs. Organizations that invest in MCP infrastructure today will be positioned to deliver next-generation customer experiences tomorrow.</p><p>The future of banking is conversational. The future is now.</p><h3>About the Author</h3><p>Building at the intersection of AI and fintech. Passionate about making financial services more accessible through intelligent automation.</p><p><strong>Connect:</strong> GitHub <a href="https://github.com/Frictionlessdev">@Frictionlessdev</a></p><h3>References</h3><ol><li>Model Context Protocol Specification — Anthropic</li><li>UK Open Banking API Standards v3.1 — Open Banking Limited</li><li>Spring Boot 3 Reference Documentation — Spring.io</li></ol><p><strong>Tags:</strong> #OpenBanking #MCP #AI #FinTech #SpringBoot #Java #Claude #LLM #APIIntegration #ConversationalAI</p><p><strong>Published on Medium</strong> | 15 min read | Advanced Level</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3f439a4b9b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Cryptographic Encryption vs. Signing for Secure APIs]]></title>
            <link>https://medium.com/@shivibh/understanding-cryptographic-encryption-vs-signing-for-secure-apis-822c0806ec1c?source=rss-2660c028d341------2</link>
            <guid isPermaLink="false">https://medium.com/p/822c0806ec1c</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[cryptography-for-dummies]]></category>
            <dc:creator><![CDATA[Shivi Bhardwaj]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 13:53:13 GMT</pubDate>
            <atom:updated>2024-11-06T02:18:32.432Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Cryptographic Encryption vs. Signing for Secure JAVA APIs</h3><p>As a Java API and microservices developer, securing your APIs requires a solid understanding of cryptographic techniques, especially encryption and digital signing. These two concepts, though related, serve distinct purposes in protecting data integrity, confidentiality, and authenticity. In this article, we’ll break down the differences between encryption and signing, explain when to use each, and provide practical examples in a Java API context.</p><h3>Why Cryptography Matters for API Security</h3><p>In the realm of API security, cryptography helps ensure that only authorized users can access or modify data, and that data remains secure during transmission. Specifically, encryption helps maintain <strong>confidentiality</strong> by making sure only authorized parties can view sensitive information, while signing provides <strong>authenticity and integrity</strong> by confirming that the data has not been altered and is indeed from a trusted source.</p><p>Let’s explore each of these mechanisms in more detail.</p><h3>1. Cryptographic Encryption</h3><h3>What Is Encryption?</h3><p>Encryption is the process of encoding data so that it can only be read by someone with the right decryption key. It’s primarily used for protecting the confidentiality of data, ensuring that even if unauthorized users access the data, they won’t be able to read it without the correct decryption key.</p><h3>How It Works</h3><p>Encryption involves transforming plaintext (original data) into ciphertext (an unreadable form) using an encryption algorithm and a key. This ciphertext can only be converted back to the original plaintext with a matching decryption key.</p><h3>Types of Encryption</h3><ul><li><strong>Symmetric Encryption</strong>: Uses the same key for both encryption and decryption (e.g., AES).</li><li><strong>Asymmetric Encryption</strong>: Uses a pair of keys — a public key for encryption and a private key for decryption (e.g., RSA).</li></ul><h3>Use Case: Encrypting Sensitive API Data</h3><p>Imagine a scenario where your API sends sensitive information, like a user’s financial data. You want to ensure that only the intended recipient can read this data, even if the API’s communication is intercepted.</p><p><strong>Example in Java using RSA Encryption</strong>:</p><pre>import javax.crypto.Cipher;<br>import java.security.KeyPair;<br>import java.security.KeyPairGenerator;<br>import java.util.Base64;<br><br>public class EncryptionExample {<br>    public static void main(String[] args) throws Exception {<br>        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(&quot;RSA&quot;);<br>        keyGen.initialize(2048);<br>        KeyPair keyPair = keyGen.generateKeyPair();<br><br>        String message = &quot;Sensitive Financial Data&quot;;<br><br>        // Encrypting the data<br>        Cipher encryptCipher = Cipher.getInstance(&quot;RSA&quot;);<br>        encryptCipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());<br>        byte[] encryptedBytes = encryptCipher.doFinal(message.getBytes());<br>        String encryptedMessage = Base64.getEncoder().encodeToString(encryptedBytes);<br><br>        System.out.println(&quot;Encrypted Message: &quot; + encryptedMessage);<br>    }<br>}</pre><p>In this example, the data is encrypted with the public key. Only the holder of the corresponding private key can decrypt and read it, ensuring that the message remains confidential.</p><h3>2. Cryptographic Signing</h3><h3>What Is Signing?</h3><p>Signing is a cryptographic process that ensures the authenticity and integrity of data. It allows the recipient to verify that the data genuinely comes from a trusted source (authenticity) and that it hasn’t been altered during transmission (integrity).</p><h3>How It Works</h3><p>Signing involves creating a <strong>digital signature</strong> of the data using a hashing algorithm and the sender’s private key. The recipient can then use the sender’s public key to verify the signature, confirming both the sender’s identity and that the data has not been tampered with.</p><h3>Use Case: Verifying API Responses</h3><p>For example, your API sends an important message to a client application. You want the client to verify that the response is from your server and has not been modified.</p><p><strong>Example in Java using RSA Signing</strong>:</p><pre><br>public class SigningExample {<br>    public static void main(String[] args) throws Exception {<br>        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(&quot;RSA&quot;);<br>        keyGen.initialize(2048);<br>        KeyPair keyPair = keyGen.generateKeyPair();<br>        PrivateKey privateKey = keyPair.getPrivate();<br><br>        String message = &quot;Important API Response&quot;;<br><br>        // Signing the message<br>        Signature sign = Signature.getInstance(&quot;SHA256withRSA&quot;);<br>        sign.initSign(privateKey);<br>        sign.update(message.getBytes());<br>        byte[] signatureBytes = sign.sign();<br>        String signature = Base64.getEncoder().encodeToString(signatureBytes);<br><br>        System.out.println(&quot;Digital Signature: &quot; + signature);<br>    }<br>}</pre><p>In this example, the message is signed with a private key, and the client can use the server’s public key to verify the signature, ensuring the response’s authenticity and integrity.</p><h3>Encryption vs. Signing: When to Use Each</h3><ul><li><strong>Use Encryption</strong> when you need to protect data confidentiality. For example, encrypt API responses or sensitive data payloads.</li><li><strong>Use Signing</strong> when you need to validate the data’s source and ensure it hasn’t been tampered with, such as validating JSON Web Tokens (JWTs) in authentication flows.</li></ul><h3>Limitations and Considerations</h3><ol><li><strong>Performance Overheads</strong>: Both encryption and signing add computational overhead. Symmetric encryption (e.g., AES) is generally faster than asymmetric encryption, but both are more efficient when properly managed.</li><li><strong>Key Management</strong>: With both encryption and signing, secure key storage is critical. Consider using a secure key management solution or service (e.g., AWS KMS or HashiCorp Vault) for sensitive key storage.</li><li><strong>Combining Techniques</strong>: Often, encryption and signing are combined for better security. For example, you might encrypt sensitive data and sign the encrypted message to ensure both confidentiality and integrity.</li></ol><h3>Conclusion</h3><p>Encryption and signing each play vital roles in securing APIs, especially in finance and healthcare, where data confidentiality, integrity, and authenticity are paramount. By understanding their differences and appropriate use cases, you can enhance your API’s security posture and protect sensitive data from unauthorized access and tampering.</p><p>If you’ve worked with JWT, OAuth, or API security challenges, I’d love to hear your thoughts or experiences in the comments. Let’s learn and secure our APIs together!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=822c0806ec1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive Error and Response Handling with Spring WebClient: A Deep Dive]]></title>
            <link>https://medium.com/@shivibh/reactive-error-and-response-handling-with-spring-webclient-a-deep-dive-cd476105d885?source=rss-2660c028d341------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd476105d885</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[webclient]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[Shivi Bhardwaj]]></dc:creator>
            <pubDate>Wed, 09 Oct 2024 14:30:02 GMT</pubDate>
            <atom:updated>2024-10-09T14:30:02.144Z</atom:updated>
            <content:encoded><![CDATA[<p>As the world shifts towards microservices and cloud-native applications, traditional synchronous programming can become a bottleneck. Spring WebClient, part of Spring WebFlux, offers a reactive and non-blocking approach to making HTTP calls, allowing your application to handle asynchronous tasks efficiently. This post will explore how to handle responses and errors reactively, using WebClient, and demonstrate the subscribe and publish patterns for managing both success and failure scenarios.</p><h4>Why Reactive Programming?</h4><p>Reactive programming allows your application to remain responsive under load by not blocking threads for I/O-bound tasks (like database queries or external API calls). With Spring WebClient, you can make HTTP calls reactively and handle responses and errors seamlessly using reactive streams.</p><h4>Setting Up Spring WebClient</h4><p>First, let’s ensure you have WebClient set up in your Spring Boot application. Here’s the typical way to create a WebClient instance:</p><pre>WebClient webClient = WebClient.builder()<br>        .baseUrl(&quot;https://api.example.com&quot;)<br>        .build();</pre><h4>Reactive Request Handling</h4><p>Let’s explore how to make a simple GET request and handle the response reactively. Here’s how you can retrieve a resource and transform the response into a Mono&lt;String&gt;:</p><pre>Mono&lt;String&gt; responseMono = webClient.get()<br>        .uri(&quot;/some-rest-resource&quot;)<br>        .retrieve()<br>        .bodyToMono(String.class);</pre><p>The method bodyToMono() returns a Mono&lt;String&gt;, which means that you’re expecting a single response item.</p><h3>Handling Responses and Errors</h3><h4>Success Handling</h4><p>To handle the response reactively, we can subscribe to the Mono and define what happens when we receive a successful response. The subscribe() method is commonly used here:</p><pre>responseMono.subscribe(<br>        successResponse -&gt; {<br>            // Handle success response<br>            System.out.println(&quot;Success: &quot; + successResponse);<br>        },<br>        error -&gt; {<br>            // Handle error response<br>            System.out.println(&quot;Error: &quot; + error.getMessage());<br>        });</pre><p>In this example, the subscribe() method takes two lambda expressions:</p><ul><li>One to handle the success (successResponse), printing the response.</li><li>Another to handle the error (error).</li></ul><h4>Error Handling</h4><p>To properly handle errors in a more controlled way, Spring WebClient provides onStatus() and onErrorResume() methods. Here’s an example:</p><pre>Mono&lt;String&gt; responseMono = webClient.get()<br>        .uri(&quot;/resource&quot;)<br>        .retrieve()<br>        .onStatus(HttpStatus::is4xxClientError, clientResponse -&gt; {<br>            // Handle 4xx errors<br>            return Mono.error(new RuntimeException(&quot;Client Error!&quot;));<br>        })<br>        .onStatus(HttpStatus::is5xxServerError, clientResponse -&gt; {<br>            // Handle 5xx errors<br>            return Mono.error(new RuntimeException(&quot;Server Error!&quot;));<br>        })<br>        .bodyToMono(String.class)<br>        .onErrorResume(e -&gt; {<br>            // Fallback logic in case of an error<br>            System.out.println(&quot;Error occurred: &quot; + e.getMessage());<br>            return Mono.just(&quot;Default fallback response&quot;);<br>        });</pre><ul><li>onStatus() checks for specific HTTP status codes (4xx and 5xx) and allows you to handle them as custom exceptions.</li><li>onErrorResume() lets you define fallback behavior if an error occurs. In this case, it returns a default response if the API call fails.</li></ul><p>To dive deeper into custom exceptions in WebClient, you can refer to my <a href="https://medium.com/p/2be5415e031e">previous blog post</a> where I explain how to structure and manage custom exceptions in your application.</p><h3>publishOn and subscribeOn: Where Do They Fit?</h3><p>In reactive programming, controlling the thread on which tasks are executed is crucial. This is where publishOn and subscribeOn come into play.</p><ul><li>subscribeOn: Defines the scheduler on which the subscription (upstream tasks) will happen.</li><li>publishOn: Controls the execution thread for downstream operations.</li></ul><p>Here’s an example that combines both:</p><pre>responseMono<br>        .subscribeOn(Schedulers.boundedElastic()) // Upstream task on different thread<br>        .publishOn(Schedulers.parallel()) // Downstream task in parallel<br>        .subscribe(<br>            successResponse -&gt; System.out.println(&quot;Success on thread: &quot; + Thread.currentThread().getName()),<br>            error -&gt; System.out.println(&quot;Error on thread: &quot; + Thread.currentThread().getName())<br>        );</pre><ul><li>Schedulers.boundedElastic() allows I/O-bound tasks to run in a non-blocking manner.</li><li>Schedulers.parallel() is suitable for CPU-bound operations.</li></ul><p>By using publishOn and subscribeOn, you can control how tasks are distributed across threads, which is crucial for performance in reactive programming.</p><h3>block() vs subscribe()</h3><p>It’s important to understand the difference between block() and subscribe() in reactive programming.</p><ul><li>block() is a synchronous call that blocks the current thread until the value is available. It is mainly used in testing or for simple use cases where reactive behavior is not needed.</li><li>subscribe() is the preferred way in a reactive application as it allows non-blocking execution.</li></ul><p>Here’s a quick comparison:</p><pre>// Synchronous blocking (not recommended for reactive)<br>String result = responseMono.block();<br><br>// Non-blocking subscription (recommended)<br>responseMono.subscribe(successResponse -&gt; {<br>    // Handle success asynchronously<br>});</pre><h3>Complete Example: Handling Success and Error Response with subscribe()</h3><p>Here’s a complete example demonstrating how to handle both success and error responses in Spring WebClient reactively using subscribe():</p><pre>public void makeReactiveRequest() {<br>    webClient.get()<br>        .uri(&quot;/resource&quot;)<br>        .retrieve()<br>        .bodyToMono(String.class)<br>        .subscribe(<br>            successResponse -&gt; {<br>                // Handle success<br>                System.out.println(&quot;Received successful response: &quot; + successResponse);<br>            },<br>            error -&gt; {<br>                // Handle error<br>                System.err.println(&quot;An error occurred: &quot; + error.getMessage());<br>            }<br>        );<br>}</pre><p>This approach ensures your application remains responsive while handling both success and error cases without blocking the main thread.</p><h3>Conclusion</h3><p>By using Spring WebClient, you can handle responses and errors reactively, making your applications more scalable and efficient. Understanding how to handle success, errors, and threading with subscribe(), onErrorResume(), and publishOn()/subscribeOn() can significantly improve the performance and resilience of your microservices.</p><p>To further explore handling custom exceptions in your applications, check out my previous post on <a href="https://medium.com/p/2be5415e031e">structuring custom exceptions in Java</a>.</p><p>Stay reactive, keep experimenting, and you’ll soon realize the power of non-blocking I/O in modern applications!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd476105d885" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Custom Exceptions in Spring WebClient: A Comprehensive Guide]]></title>
            <link>https://medium.com/@shivibh/managing-custom-exceptions-in-spring-webclient-a-comprehensive-guide-2be5415e031e?source=rss-2660c028d341------2</link>
            <guid isPermaLink="false">https://medium.com/p/2be5415e031e</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[webclient]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Shivi Bhardwaj]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 13:23:08 GMT</pubDate>
            <atom:updated>2024-09-28T13:23:08.696Z</atom:updated>
            <content:encoded><![CDATA[<p>In the development of modern web applications with Spring Boot, efficiently managing external API calls and addressing errors is vital. Spring&#39;s WebClient offers a strong reactive approach for handling HTTP requests and responses. Nevertheless, developers often encounter difficulties with error handling, particularly with custom exceptions.</p><p>This blog will guide you through the steps to:</p><ol><li>Propagate custom exceptions without them being wrapped in a <em>ReactiveException</em>.</li><li>Handle exceptions in a controller.</li><li>Test the service using <em>StepVerifier</em> for reactive flows instead of traditional <em>assertThrows</em>.</li></ol><p><strong>Step 1</strong>: Using WebClient in the Service Layer</p><p><em>WebClient</em> allows you to handle the HTTP response reactively. To throw a custom exception based on the HTTP status code (e.g., for 4xx or 5xx responses), you can use the <em>onStatus()</em> method, which checks the response status and raises an exception if needed.</p><p>Here’s a simple implementation in the service class.</p><pre>@Service<br>public class MyService {<br><br>    private final WebClient webClient;<br><br>    public MyService(WebClient webClient) {<br>        this.webClient = webClient;<br>    }<br><br>    public Mono&lt;String&gt; getDataFromApi() {<br>        return webClient.get()<br>                .uri(&quot;/data&quot;)<br>                .retrieve()<br>                .onStatus(HttpStatusCode::isError, clientResponse -&gt; <br>                    Mono.error(new CustomException(&quot;Failed to retrieve data from API&quot;))<br>                )<br>                .bodyToMono(String.class);<br>    }<br>}</pre><blockquote>Key Points:</blockquote><blockquote>Mono.error(): This method allows you to return an error signal in reactive streams, making it possible to propagate a custom exception.</blockquote><blockquote>Custom Exception Propagation: The CustomException is directly thrown inside the onStatus() block, ensuring that it reaches the caller without being wrapped in any reactive infrastructure exceptions.</blockquote><p><strong>Step 2</strong>: Invoking the Service in the Controller</p><p>Now that we’ve set up the service layer to throw <em>CustomException</em>, we’ll invoke it from the controller. You can handle the exception directly inside the controller using reactive error-handling methods like <em>onErrorResume()</em>.</p><pre>@RestController<br>public class MyController {<br><br>    private final MyService myService;<br><br>    public MyController(MyService myService) {<br>        this.myService = myService;<br>    }<br><br>    @GetMapping(&quot;/api/data&quot;)<br>    public Mono&lt;String&gt; getData() {<br>        return myService.getDataFromApi()<br>                .onErrorResume(CustomException.class, ex -&gt; {<br>                    return Mono.just(&quot;Error occurred: &quot; + ex.getMessage());<br>                });<br>    }<br>}</pre><blockquote><em>Key Points:</em></blockquote><blockquote>Error Handling: The onErrorResume() method catches the CustomException and allows you to provide a fallback response or handle the error gracefully.</blockquote><blockquote>Reactive Flow: The entire controller method is non-blocking, making it efficient and suitable for high-performance applications.</blockquote><p><strong>Step 3</strong>: Testing the Service with <em>StepVerifier</em></p><p>Traditionally, <em>assertThrows()</em> is used to test exceptions in Java. However, for reactive programming, <em>StepVerifier</em> is more suitable as it integrates smoothly with non-blocking operations. You can use it to test a service method that throws a <em>CustomException</em> when an API call fails.</p><pre>public class MyServiceTest {<br><br>    private MockWebServer mockWebServer;<br>    private MyService myService;<br><br>    @BeforeEach<br>    public void setUp() throws Exception {<br>        mockWebServer = new MockWebServer();<br>        mockWebServer.start();<br><br>        WebClient webClient = WebClient.builder()<br>                .baseUrl(mockWebServer.url(https://medium.com/&quot;/&quot;).toString())<br>                .build();<br><br>        myService = new MyService(webClient);<br>    }<br><br>    @AfterEach<br>    public void tearDown() throws Exception {<br>        mockWebServer.shutdown();<br>    }<br><br>    @Test<br>    public void testGetDataFromApiThrowsCustomException() {<br>        // Arrange: Simulate a 500 Internal Server Error<br>        mockWebServer.enqueue(new MockResponse()<br>                .setResponseCode(500)<br>                .setBody(&quot;Internal Server Error&quot;));<br><br>        // Act &amp; Assert: Use StepVerifier to test the reactive Mono<br>        StepVerifier.create(myService.getDataFromApi())<br>                .expectError(CustomException.class)<br>                .verify();<br>    }<br>}</pre><blockquote><strong>Why Use StepVerifier?</strong></blockquote><blockquote>Handles Reactive Flows: StepVerifier is specifically designed for testing reactive types like Mono and Flux.</blockquote><blockquote>Non-blocking Testing: It works seamlessly with non-blocking code, making it the perfect tool to test WebClient and other reactive streams.</blockquote><blockquote>Fine-grained Control: You can assert not only exceptions but also specific values and sequences in the reactive stream.</blockquote><p><strong>Step 4</strong>: Global Exception Handling (Optional)</p><p>For consistent error handling across your application, you can implement a global exception handler using <em>@RestControllerAdvice</em>. This centralizes your error-handling logic and ensures that all controllers handle exceptions in the same way.</p><pre>@RestControllerAdvice<br>public class GlobalExceptionHandler {<br><br>    @ExceptionHandler(CustomException.class)<br>    public Mono&lt;ResponseEntity&lt;String&gt;&gt; handleCustomException(CustomException ex) {<br>        return Mono.just(<br>                ResponseEntity.status(HttpStatus.BAD_REQUEST)<br>                        .body(&quot;Custom Error: &quot; + ex.getMessage())<br>        );<br>    }<br>}</pre><p><strong>Conclusion</strong></p><p>In reactive applications, managing errors with <em>WebClient</em> necessitates a distinct strategy from that of conventional blocking code. Utilizing <em>Mono.error()</em> to disseminate exceptions and employing <em>StepVerifier</em> for their verification helps maintain your code as non-blocking, efficient, and verifiable.</p><blockquote><strong>Key takeaways:</strong></blockquote><blockquote>Use Mono.error() to throw exceptions in reactive streams.</blockquote><blockquote>Handle exceptions using onErrorResume() in controllers or global exception handlers.</blockquote><blockquote>Test reactive code with StepVerifier, which provides better control than assertThrows() for non-blocking operations.</blockquote><blockquote>This step-by-step guide should help you build robust, reactive Spring Boot applications with proper error handling and testing strategies. Happy coding!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2be5415e031e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>