RestController throws different exceptions for other errors
authorKai Moritz <kai@juplo.de>
Tue, 14 Jan 2020 23:45:15 +0000 (00:45 +0100)
committerKai Moritz <kai@juplo.de>
Thu, 16 Jan 2020 10:18:03 +0000 (11:18 +0100)
* Goal: distinguish between errors, that occure during the fetching of the
  data and errors, that may occure elswhere in RemoteController
* Added an unit-test, that verifies the distinction
* Fixed the behavior of RestController accordingly

src/main/java/de/juplo/demo/RestController.java
src/test/java/de/juplo/demo/RestControllerTest.java

index f7f63a6..f6cddca 100644 (file)
@@ -35,6 +35,15 @@ public class RestController
             {
               if(t.getClass().equals(NotFound.class))
                 return Mono.error(t);
+              if(!(t instanceof WebClientResponseException))
+                return
+                    Mono.error(
+                        WebClientResponseException.create(
+                            500,
+                            "Internal Server Error - Cause: " + t.getMessage(),
+                            null,
+                            null,
+                            null));
 
               return
                   Mono.error(
index 4b4526a..edf2280 100644 (file)
@@ -11,6 +11,7 @@ import org.mockito.Mockito;
 import static org.mockito.Mockito.when;
 import org.springframework.http.HttpStatus;
 import org.springframework.web.reactive.function.client.WebClientResponseException;
+import org.springframework.web.reactive.function.client.WebClientResponseException.InternalServerError;
 import org.springframework.web.reactive.function.client.WebClientResponseException.NotFound;
 import org.springframework.web.reactive.function.client.WebClientResponseException.ServiceUnavailable;
 import reactor.core.publisher.Mono;
@@ -108,6 +109,25 @@ public class RestControllerTest
         .verify();
   }
 
+  @Test
+  @DisplayName("Internal error while fetching data from remote-server")
+  void testOtherErrors()
+  {
+    Mono<String> mono = Mono.error(new RuntimeException("Boom!"));
+    when(service.getRemoteText("foo")).thenReturn(mono);
+
+    Mono<String> result = controller.fetch("foo");
+
+    StepVerifier
+        .create(result)
+        .expectErrorSatisfies((t) ->
+        {
+          assertThat(t).isInstanceOf(InternalServerError.class);
+          assertThat(t.getMessage()).isEqualTo("500 Internal Server Error - Cause: Boom!");
+        })
+        .verify();
+  }
+
 
   WebClientResponseException exception(int status)
   {