@Controller("/books")
class BooksController {
@Get("/{isbn}")
HttpResponse find(String isbn) {
if (isbn == "1680502395") {
Map<String, Object> m = new HashMap<>()
m.put("status", 401)
m.put("error", "Unauthorized")
m.put("message", "No message available")
m.put("path", "/books/"+isbn)
return HttpResponse.status(HttpStatus.UNAUTHORIZED).body(m)
return HttpResponse.ok(new Book("1491950358", "Building Microservices"))
}
}
@Test
public void afterAnHttpClientExceptionTheResponseBodyCanBeBoundToAPOJO() {
try {
client.toBlocking().exchange(HttpRequest.GET("/books/1680502395"),
Argument.of(Book.class), (1)
Argument.of(CustomError.class)); (2)
} catch (HttpClientResponseException e) {
assertEquals(HttpStatus.UNAUTHORIZED, e.getResponse().getStatus());
Optional<CustomError> jsonError = e.getResponse().getBody(CustomError.class);
assertTrue(jsonError.isPresent());
assertEquals("Unauthorized", jsonError.get().error);
assertEquals("No message available", jsonError.get().message);
assertEquals("/books/1680502395", jsonError.get().path);
}
}
"after an httpclient exception the response body can be bound to a POJO" {
try {
client.toBlocking().exchange(HttpRequest.GET<Any>("/books/1680502395"),
Argument.of(Book::class.java), (1)
Argument.of(CustomError::class.java)) (2)
} catch (e: HttpClientResponseException) {
e.response.status shouldBe HttpStatus.UNAUTHORIZED
}