From afa69a40ee5a9237b02acd29f812dbabecf5bec7 Mon Sep 17 00:00:00 2001 From: Ryan Bergman Date: Sat, 26 Nov 2022 08:31:13 -0600 Subject: [PATCH] issue #451 pass original failure reason to new mapped response in ifFailure --- .../java/BehaviorTests/ErrorParsingTest.java | 16 ++++++++++++++++ .../java/kong/unirest/core/BaseResponse.java | 4 +++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/unirest-bdd-tests/src/test/java/BehaviorTests/ErrorParsingTest.java b/unirest-bdd-tests/src/test/java/BehaviorTests/ErrorParsingTest.java index 7d062877..51d78ea3 100644 --- a/unirest-bdd-tests/src/test/java/BehaviorTests/ErrorParsingTest.java +++ b/unirest-bdd-tests/src/test/java/BehaviorTests/ErrorParsingTest.java @@ -38,6 +38,22 @@ class ErrorParsingTest extends BddTest { private boolean errorCalled; + @Test + void passParsingErrorsOnInFalure() { + MockServer.setStringResponse("not json"); + + Unirest.get(MockServer.GET) + .asObject(RequestCapture.class) + .ifFailure(String.class, r -> + { + assertTrue(r.getParsingError().isPresent()); + assertTrue(r.getParsingError().get().getMessage().contains("jackson")); + assertEquals("not json", r.getParsingError().get().getOriginalBody()); + } + ) + .ifSuccess(s -> fail("no")); + } + @Test void parsingAnAlternativeErrorObject() { MockServer.setJsonAsResponse(new ErrorThing("boom!")); diff --git a/unirest/src/main/java/kong/unirest/core/BaseResponse.java b/unirest/src/main/java/kong/unirest/core/BaseResponse.java index fd421fd8..5449ccfe 100644 --- a/unirest/src/main/java/kong/unirest/core/BaseResponse.java +++ b/unirest/src/main/java/kong/unirest/core/BaseResponse.java @@ -155,7 +155,9 @@ private String getErrorBody() { public HttpResponse ifFailure(Class errorClass, Consumer> consumer) { if (!isSuccess()) { E error = mapError(errorClass); - consumer.accept(new BasicResponse(this, error)); + BasicResponse br = new BasicResponse(this, error); + getParsingError().ifPresent(p -> br.setParsingException(p.getOriginalBody(), p)); + consumer.accept(br); } return this; }