title: How to perform an action only if the Mono is empty and throw an error if not empty
body: <p>I'm trying to convert a project to use Spring WebFlux and am running into a problem getting some basic business logic working.  I have a repository layer that is responsible for retrieving / persisting records and a service layer that is responsible for the business rules of the application.  What I want to do (in the service) layer is check if a user already exists for the given username.  If so, I want to respond with an error.  If not, I want to allow the insert to happen.</p>
  
  <p>I call a method on the repository layer that will find a user by username and if not found it will return an empty Mono.  This is working as expected; however, I have tried various combinations of flatMap and (defaultIfEmpty and swithIfEmpty) but am unable to get it to compile / build.</p>
  
  <pre class="lang-java prettyprint-override"><code>    public Mono&lt;User&gt; insertUser(User user) {
          return userRepository.findByUsername(user.username())
              .flatMap(__ -&gt; Mono.error(new DuplicateResourceException("User already exists with username [" + user.username() + "]")))
              .switchIfEmpty(userRepository.insertUser(user));
      }
  </code></pre>
  
  <p>The error that I'm getting is that <code>Mono&lt;Object&gt; cannot be converted to Mono&lt;User&gt;</code>, so the <code>swithIfEmpty</code> doesn't seem to reflect the appropriate type and casting doesn't seem to work either.</p>