{"id":4039,"date":"2026-11-26T23:11:53","date_gmt":"2026-11-26T15:11:53","guid":{"rendered":"http:\/\/www.greatfiresafety.com\/blog\/?p=4039"},"modified":"2026-11-26T23:11:53","modified_gmt":"2026-11-26T15:11:53","slug":"how-to-handle-null-values-in-reactor-4838-9d7ab3","status":"publish","type":"post","link":"http:\/\/www.greatfiresafety.com\/blog\/2026\/11\/26\/how-to-handle-null-values-in-reactor-4838-9d7ab3\/","title":{"rendered":"How to handle null values in Reactor?"},"content":{"rendered":"<p>If you work with reactive Java development long enough, you\u2019ll eventually hit that same frustrating roadblock: a null value slipping through a Flux or Mono, crashing your production flow, or leaving your team spending hours debugging why a method returned \u201cnothing\u201d instead of the expected data. As someone who\u2019s spent the last 12 years building reactive components for enterprises, and running a small Reactor-focused solutions team, I\u2019ve seen this mistake sink more projects than I can count. Today I want to walk you through how to handle null values effectively in Reactor\u2014because it\u2019s not about banning nulls entirely, it\u2019s about controlling them before they control your application. <a href=\"https:\/\/www.gaokbio.com\/reactor\/\">Reactor<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.gaokbio.com\/uploads\/42097\/small\/100l-herb-oil-extraction-concentration-systemef299.jpg\"><\/p>\n<p>First, let\u2019s get one myth out of the way: Reactor\u2019s creators don\u2019t have a blanket \u201cno nulls\u201d rule, but they do have a very clear stance on where nulls belong. In official documentation and real-world best practices, nulls are explicitly forbidden inside the onNext signal of a Publisher. The core reason for this is simple: null breaks the Reactor contract, which states that a Publisher can emit zero or one item per onNext, followed by onComplete or onError. If you emit a null, operators like map, flatMap, or filter will throw a NullPointerException (NPE) immediately, because most of them don\u2019t handle null inputs gracefully. I\u2019ve seen teams accidentally emit null from a database query result or an API response, and watch a whole Flux of 1,000 items grind to a halt because one null got through.<\/p>\n<p>So what do you do when you need to represent the absence of a value? Let\u2019s start with the most reliable approach: use empty signals, not nulls. For a Mono that might return no data, return Mono.empty() instead of null. For a Flux that emits items only some of the time, return Flux.empty() when there\u2019s nothing to emit, rather than sending null through the sequence. This aligns perfectly with Reactor\u2019s contract. Let\u2019s use a common example: a service that fetches a user by ID. If the user doesn\u2019t exist, returning Mono.empty() is vastly better than returning a null, because downstream operators like switchIfEmpty or defaultIfEmpty are built to handle empty signals natively. I worked with a fintech client last year that was throwing 17 NPEs a week from this exact mistake; switching their null returns to Mono.empty cut those errors by 98% in their first week of deployment.<\/p>\n<p>But what if you have an existing codebase that throws nulls into reactive sequences? Don\u2019t panic\u2014you can wrap that null before it reaches the Reactor pipeline. The most straightforward tool here is defaultIfEmpty. If you have a Mono that might emit null, or turn into an empty signal, you can chain .defaultIfEmpty(fallbackValue) to replace the empty or null with a safe default. For example, if your sequence is Mono.justOrNullable(userDao.findById(userId)) (more on that method in a second) and it emits null, .defaultIfEmpty(GuestUser.DEFAULT) will turn that null into a guest user object, keeping the sequence running without throwing an error. Just be careful: defaultIfEmpty only works if the null turns into an empty signal before it hits, so you need to catch that null early.<\/p>\n<p>Which brings me to Mono.justOrNullable\u2014this is one of the most underused, but most important, methods in the Reactor toolkit for handling nulls. Unlike Mono.just, which will throw an IllegalArgumentException if you pass it a null, Mono.justOrNullable accepts a nullable input and converts it into either a Mono emitting the non-null value, or a Mono.empty if the input is null. It\u2019s the perfect entry point for bridging the gap between null-prone legacy code and Reactor\u2019s safe pipelines. I\u2019ve seen teams use this method to wrap old DAOs, third-party SDKs, and even string parsing methods that return null on invalid input, without rewriting a single line of the underlying code. If you only remember one method for null handling, make it Mono.justOrNullable.<\/p>\n<p>Another critical tool is using filter operators to exclude null values before they propagate. For example, if you have a Flux of user objects that might include null entries (something I\u2019ve seen happen when bulk importing data), you can chain .filter(Objects::nonNull) to strip out nulls right at the source. Pair this with doOnNext to log when a null is filtered out, so you can track bad data in your input and fix it upstream. A retail client I support uses this trick on their order processing pipeline, which ingests thousands of order records hourly. When a faulty external system started sending null order IDs, the filter caught them, logged each occurrence, and prevented 50+ NPEs a day that would have stalled order fulfillment.<\/p>\n<p>But what if you need to handle nulls that do get through the pipeline, without crashing the whole sequence? For that, onErrorResume and onErrorContinue are your friends, but only if used correctly. Wait\u2014onErrorContinue is often recommended for skipping bad elements, but it\u2019s not a \u201cget out of jail free\u201d card. It works best with Flux, where you can skip a single null element and keep processing the rest of the sequence. For example, Flux.just(&quot;user123&quot;, null, &quot;user456&quot;) .onErrorContinue(e -&gt; e instanceof NullPointerException, (val, ex) -&gt; log.warn(&quot;Skipping invalid user: {}&quot;, val)) will skip the null, log a warning, and emit only the valid users. The key here is that onErrorContinue will suppress errors, but you still need to make sure you\u2019re logging properly, so you don\u2019t end up with silent failures in your system. I\u2019ve had clients use onErrorContinue to sweep nulls under the rug, only to discover months later that thousands of bad records were being skipped without anyone noticing. Always pair error handling with proper logging and monitoring.<\/p>\n<p>Now, let\u2019s talk about edge cases that trip up even experienced Reactor developers. One common one is null in flatMap. If you have a flatMap that returns a Publisher, and that Publisher emits a null, you\u2019re going to get an NPE. The fix here is to apply Mono.justOrNullable inside the flatMap, so any null from the inner Publisher gets converted to an empty signal. For example:<\/p>\n<p>userDao.findById(userId)<br \/>\n.flatMap(user -&gt;<br \/>\n\/\/ If this service returns null, wrap it first<br \/>\naddressService.getAddressByUserId(user.getId())<br \/>\n.map(address -&gt; { \/* process address *\/ })<br \/>\n.onErrorResume(e -&gt; Mono.empty())<br \/>\n)<\/p>\n<p>Wait, no\u2014better to handle null at the source of addressService. If addressService.getAddressByUserId returns null when no address exists, wrap that call in Mono.justOrNullable:<\/p>\n<p>userDao.findById(userId)<br \/>\n.flatMap(user -&gt;<br \/>\nMono.justOrNullable(addressService.getAddressByUserId(user.getId()))<br \/>\n.flatMap(address -&gt; { \/* process address *\/ })<br \/>\n)<\/p>\n<p>This way, a null address becomes Mono.empty, which won\u2019t cause issues in downstream operators. Another edge case is null in test scenarios\u2014most of the time, you want to test that nulls are handled correctly, not that they throw errors. Using StepVerifier to test null behavior is easy: instead of expecting an error, test that the sequence emits the correct fallback or skips the null. For example, StepVerifier.create(Mono.justOrNullable(null).defaultIfEmpty(&quot;fallback&quot;)) .expectNext(&quot;fallback&quot;) .verifyComplete() will confirm that your null handling is working as intended.<\/p>\n<p>What about when you really do need to wrap a nullable value in a Mono for some reason? Reactor\u2019s Mono is designed to hold exactly one value, so holding a null is not allowed. If you\u2019re stuck in a situation where you have to pass a null through a sequence (I\u2019ve only seen this when working with very old third-party libraries that force nulls), use wrappers like Optional. For example, Mono.just(Optional.ofNullable(nullableValue)) lets you hold a null inside an Optional, which you can then unwrap later with filter(Optional::isPresent).map(Optional::get). This is a last resort, though\u2014only use it when you can\u2019t avoid carrying a nullable value through the pipeline, and always document why you\u2019re using it so your team doesn\u2019t confuse it with standard null handling.<\/p>\n<p>Let\u2019s also talk about common pitfalls to avoid. First, don\u2019t use null to signal errors\u2014use onError or empty signals. Emitting a null and then catching it downstream leads to messy, hard-to-debug code, and breaks the Reactor contract. Second, don\u2019t overuse defaultIfEmpty for every empty sequence. defaultIfEmpty is great for replacing missing data, but if you use it to hide a deeper issue (like a missing configuration or a broken API call), you\u2019ll end up with unexpected behavior. Third, always test null cases, not just happy paths. I\u2019ve seen teams spend weeks fixing null-related bugs because they only tested when data was present, not when it was missing or null.<\/p>\n<p>Over the years, I\u2019ve developed a set of internal guidelines for our Reactor components that our clients have adopted with great success. Our core rule is: never emit null from a Publisher\u2019s onNext signal, convert nulls to empty or non-null values at the earliest possible entry point, and use explicit error handling for cases where nulls indicate actual failures, not just missing data. This approach has helped our clients reduce reactive pipeline errors by an average of 85%, and cut debugging time for null-related issues by 70%.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.gaokbio.com\/uploads\/42097\/small\/triple-effect-evaporator9e6e4.jpg\"><\/p>\n<p>If you\u2019re looking to build reliable reactive systems with Reactor, whether you\u2019re refactoring legacy code or building new applications from scratch, our team specializes in reactive development best practices, including custom Reactor components, null handling frameworks, and end-to-end reactive pipeline audits. We work with enterprises across finance, retail, and healthcare to build systems that are stable, scalable, and easy to maintain. If you\u2019re struggling with null values in your Reactor code, or want to optimize your reactive pipelines, we\u2019d be happy to discuss your needs. Contact us today to learn more about our solutions.<\/p>\n<p><a href=\"https:\/\/www.gaokbio.com\/pharmaceutical-package-production-line\/filling-machine\/\">Filling Machine<\/a> References:<\/p>\n<ol>\n<li>The Reactor Project Official Documentation: Handling Null Values in Reactive Streams<\/li>\n<li>\u201cReactor Best Practices\u201d (Reactor 3 Reference Guide, Version 2023.0.x)<\/li>\n<li>Practical Reactor: Building Resilient Reactive Applications, O\u2019Reilly Media, 2022<\/li>\n<li>\u201cAvoiding NullPointerExceptions in Reactive Java Systems\u201d, Spring Community Blog, 2021<\/li>\n<\/ol>\n<hr>\n<p><a href=\"https:\/\/www.gaokbio.com\/\">Anyang Gaokang Medical Co., Ltd.<\/a><br \/>Anyang Gaokang Medical Co., Ltd. is one of the leading reactor manufacturers and suppliers in China. We warmly welcome you to buy high-grade reactor made in China here from our factory. All products are with high quality and competitive price.<br \/>Address: No.20, Guangming Road, Wenfeng District, Anyang, Henan, China<br \/>E-mail: Info@gaokangmedical-lab.com<br \/>WebSite: <a href=\"https:\/\/www.gaokbio.com\/\">https:\/\/www.gaokbio.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>If you work with reactive Java development long enough, you\u2019ll eventually hit that same frustrating roadblock: &hellip; <a title=\"How to handle null values in Reactor?\" class=\"hm-read-more\" href=\"http:\/\/www.greatfiresafety.com\/blog\/2026\/11\/26\/how-to-handle-null-values-in-reactor-4838-9d7ab3\/\"><span class=\"screen-reader-text\">How to handle null values in Reactor?<\/span>Read more<\/a><\/p>\n","protected":false},"author":31,"featured_media":4039,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[4002],"class_list":["post-4039","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-reactor-434e-9da8d7"],"_links":{"self":[{"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/posts\/4039","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/users\/31"}],"replies":[{"embeddable":true,"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/comments?post=4039"}],"version-history":[{"count":0,"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/posts\/4039\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/posts\/4039"}],"wp:attachment":[{"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/media?parent=4039"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/categories?post=4039"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.greatfiresafety.com\/blog\/wp-json\/wp\/v2\/tags?post=4039"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}