com.nike.backstopper.apierror.ApiErrorWithMetadata Java Examples

The following examples show how to use com.nike.backstopper.apierror.ApiErrorWithMetadata. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateValidationErrorsForMethodArgumentNotValidException() {
    MethodParameter methodParam = mock(MethodParameter.class);
    BindingResult bindingResult = mock(BindingResult.class);

    List<ObjectError> errorsList = Collections.singletonList(
        new FieldError("someObj", "someField", testProjectApiErrors.getMissingExpectedContentApiError().getName())
    );
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    MethodArgumentNotValidException ex = new MethodArgumentNotValidException(methodParam, bindingResult);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    validateResponse(result, true, Collections.singletonList(
        new ApiErrorWithMetadata(testProjectApiErrors.getMissingExpectedContentApiError(),
                                 Pair.of("field", "someField"))
    ));
    verify(bindingResult).getAllErrors();
}
 
Example #2
Source File: BackstopperRiposteFrameworkErrorHandlerListenerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void should_handle_RequestTooBigException() {
    // given
    String exMsg = UUID.randomUUID().toString();
    RequestTooBigException ex = new RequestTooBigException(exMsg);

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    assertThat(result.shouldHandleResponse).isTrue();
    assertThat(result.errors).isEqualTo(singletonError(
        new ApiErrorWithMetadata(testProjectApiErrors.getMalformedRequestApiError(),
                                 Pair.of("cause", "The request exceeded the maximum payload size allowed"))
    ));

    assertThat(result.extraDetailsForLogging.get(0).getLeft()).isEqualTo("exception_message");
    assertThat(result.extraDetailsForLogging.get(0).getRight()).isEqualTo(exMsg);

    assertThat(result.extraDetailsForLogging.get(1).getLeft()).isEqualTo("decoder_exception");
    assertThat(result.extraDetailsForLogging.get(1).getRight()).isEqualTo("true");
}
 
Example #3
Source File: BackstopperRiposteFrameworkErrorHandlerListener.java    From riposte with Apache License 2.0 6 votes vote down vote up
protected @NotNull ApiError generateTooLongFrameApiError(@NotNull TooLongFrameException ex) {
    String exMessage = String.valueOf(ex.getMessage());
    Integer tooLongFrameMaxSize = extractTooLongFrameMaxSizeFromExceptionMessage(ex);
    Map<String, Object> maxSizeMetadata = new HashMap<>();
    if (tooLongFrameMaxSize != null) {
        maxSizeMetadata.put("max_length_allowed", tooLongFrameMaxSize);
    }

    // If we detect it's complaining about HTTP header size then throw the ApiError that maps to a
    //      431 HTTP status code.
    if (exMessage.startsWith("HTTP header is larger than")) {
        return new ApiErrorWithMetadata(
            TOO_LONG_FRAME_HEADER_API_ERROR_BASE,
            maxSizeMetadata
        );
    }

    // It wasn't complaining about HTTP header size (or we didn't detect it for some reason). Return the
    //      generic "too long line" ApiError that maps to a 400.
    return new ApiErrorWithMetadata(
        TOO_LONG_FRAME_LINE_API_ERROR_BASE,
        maxSizeMetadata
    );
}
 
Example #4
Source File: VerifyCornerCasesComponentTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void invalid_http_call_with_invalid_URL_escaping_should_result_in_expected_400_error() throws Exception {
    // given
    // Incorrectly escaped URLs cause a blowup in RequestInfoImpl when it tries to decode the URL. We can trigger
    //      this by putting a % character that is not followed by a proper escape sequence.
    NettyHttpClientRequestBuilder request = request()
        .withMethod(HttpMethod.GET)
        .withUri("%notAnEscapeSequence");

    // when
    NettyHttpClientResponse response = request.execute(downstreamServerConfig.endpointsPort(), 3000);

    // then
    verifyErrorReceived(response.payload,
                        response.statusCode,
                        new ApiErrorWithMetadata(SampleCoreApiError.MALFORMED_REQUEST,
                                                 Pair.of("cause", "Invalid HTTP request"))
    );
}
 
Example #5
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        // We can't expect the bad_property_name=requiredQueryParamValue metadata like we do in Spring Web MVC,
        //      because Spring WebFlux doesn't add it to the TypeMismatchException cause.
        MapBuilder.builder("bad_property_value", (Object) "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #6
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #7
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #8
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #9
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
        .when()
            .get()
        .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #10
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
        .when()
            .get()
        .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #11
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #12
Source File: VerifyExpectedErrorsAreReturnedComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing() {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #13
Source File: OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldHandleException_returns_MALFORMED_REQUEST_for_MissingServletRequestPartException() {
    // given
    String partName = UUID.randomUUID().toString();
    MissingServletRequestPartException ex = new MissingServletRequestPartException(partName);

    ApiError expectedResult = new ApiErrorWithMetadata(
        testProjectApiErrors.getMalformedRequestApiError(),
        Pair.of("missing_required_part", partName)
    );

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    validateResponse(result, true, singletonList(expectedResult));
}
 
Example #14
Source File: BackstopperSpring4WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #15
Source File: BackstopperSpring4WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #16
Source File: BackstopperSpringboot2WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #17
Source File: BackstopperSpring5WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #18
Source File: BackstopperSpring5WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #19
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateValidationErrorsForBindException() {
    BindingResult bindingResult = mock(BindingResult.class);

    ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError();
    ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError();
    ApiError notAFieldError = testProjectApiErrors.getGenericBadRequestApiError();
    List<ObjectError> errorsList = Arrays.asList(
            new FieldError("someObj", "someField", someFieldError.getName()),
            new FieldError("otherObj", "otherField", otherFieldError.getName()),
            new ObjectError("notAFieldObject", notAFieldError.getName())
    );
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    BindException ex = new BindException(bindingResult);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    validateResponse(result, true, Arrays.asList(
        new ApiErrorWithMetadata(someFieldError, Pair.of("field", "someField")),
        new ApiErrorWithMetadata(otherFieldError, Pair.of("field", "otherField")),
        notAFieldError
    ));
    verify(bindingResult).getAllErrors();
}
 
Example #20
Source File: BackstopperSpringboot2WebFluxComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #21
Source File: BackstopperSpringboot1ComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_TYPE_CONVERSION_ERROR_is_thrown_when_framework_cannot_convert_type(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .queryParam("requiredQueryParamValue", "not-an-integer")
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(response, new ApiErrorWithMetadata(
        SampleCoreApiError.TYPE_CONVERSION_ERROR,
        MapBuilder.builder("bad_property_name", (Object)"requiredQueryParamValue")
                  .put("bad_property_value", "not-an-integer")
                  .put("required_type", "int")
                  .build()
    ));
}
 
Example #22
Source File: BackstopperSpringboot1ComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #23
Source File: BackstopperSpringboot2WebMvcComponentTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@UseDataProvider("serverScenarioDataProvider")
@Test
public void verify_MALFORMED_REQUEST_is_thrown_when_required_data_is_missing(
    ServerScenario scenario
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(scenario.serverPort)
            .basePath(SAMPLE_PATH + WITH_REQUIRED_QUERY_PARAM_SUBPATH)
            .log().all()
            .when()
            .get()
            .then()
            .log().all()
            .extract();

    verifyErrorReceived(
        response,
        new ApiErrorWithMetadata(
            SampleCoreApiError.MALFORMED_REQUEST,
            Pair.of("missing_param_type", "int"),
            Pair.of("missing_param_name", "requiredQueryParamValue")
        )
    );
}
 
Example #24
Source File: ClientDataValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnGENERIC_SERVICE_ERRORForViolationThatDoesNotMapToApiError() {
    ConstraintViolation<Object> violation = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation", NotNull.class, "I_Am_Invalid");
    ClientDataValidationError ex = new ClientDataValidationError(Arrays.<Object>asList(new SomeValidatableObject("someArg1", "someArg2")), Collections.singletonList(violation), null);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);
    validateResponse(result, true, Collections.<ApiError>singletonList(
        // We expect it to be the generic error, with some metadata about the field that had an issue
        new ApiErrorWithMetadata(testProjectApiErrors.getGenericServiceError(), Pair.of("field", (Object)"path.to.violation"))
    ));
}
 
Example #25
Source File: BackstopperRiposteFrameworkErrorHandlerListenerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void shouldHandleInvalidHttpRequestExceptionWithNonNullCause(boolean useTooLongFrameExceptionAsCause) {
    // given
    Throwable cause = (useTooLongFrameExceptionAsCause)
                      ? new TooLongFrameException("TooLongFrameException occurred")
                      : new RuntimeException("runtime exception");
    String expectedCauseMetadataMessage = (useTooLongFrameExceptionAsCause)
                                          ? listener.TOO_LONG_FRAME_LINE_METADATA_MESSAGE
                                          : "Invalid HTTP request";
    String outerExceptionMessage = "message - " + UUID.randomUUID().toString();

    ApiError expectedApiErrorBase = (useTooLongFrameExceptionAsCause)
                                    ? listener.TOO_LONG_FRAME_LINE_API_ERROR_BASE
                                    : testProjectApiErrors.getMalformedRequestApiError();

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(
        new InvalidHttpRequestException(outerExceptionMessage, cause)
    );

    // then
    assertThat(result.shouldHandleResponse).isTrue();
    assertThat(result.errors).isEqualTo(singletonError(
        new ApiErrorWithMetadata(expectedApiErrorBase,
                                 Pair.of("cause", expectedCauseMetadataMessage))
    ));

    assertThat(result.extraDetailsForLogging.get(0).getLeft()).isEqualTo("exception_message");
    assertThat(result.extraDetailsForLogging.get(0).getRight()).isEqualTo(outerExceptionMessage);

    assertThat(result.extraDetailsForLogging.get(1).getLeft()).isEqualTo("exception_cause_details");
    assertThat(result.extraDetailsForLogging.get(1).getRight()).isEqualTo(cause.toString());
}
 
Example #26
Source File: BackstopperRiposteFrameworkErrorHandlerListenerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleInvalidHttpRequestExceptionWithNullCause() {
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(new InvalidHttpRequestException("message", null));
    assertThat(result.shouldHandleResponse).isTrue();
    assertThat(result.errors).isEqualTo(singletonError(
        new ApiErrorWithMetadata(testProjectApiErrors.getMalformedRequestApiError(),
                                 Pair.of("cause", "Invalid HTTP request"))
    ));

    assertThat(result.extraDetailsForLogging.get(0).getLeft()).isEqualTo("exception_message");
    assertThat(result.extraDetailsForLogging.get(0).getRight()).isEqualTo("message");

    assertThat(result.extraDetailsForLogging.get(1).getLeft()).isEqualTo("exception_cause_details");
    assertThat(result.extraDetailsForLogging.get(1).getRight()).isEqualTo("NO_CAUSE");
}
 
Example #27
Source File: BackstopperRiposteFrameworkErrorHandlerListenerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void should_handle_IncompleteHttpCallTimeoutException() {
    verifyExceptionHandled(new IncompleteHttpCallTimeoutException(4242), singletonError(
        new ApiErrorWithMetadata(testProjectApiErrors.getMalformedRequestApiError(),
                                 Pair.of("cause", "Unfinished/invalid HTTP request"))
    ));
}
 
Example #28
Source File: BackstopperRiposteFrameworkErrorHandlerListenerTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
public ApiError expectedApiError(BackstopperRiposteFrameworkErrorHandlerListener listener) {
    ApiError base = baseErrorRetriever.apply(listener);
    Map<String, Object> maxSizeMetadata = new HashMap<>();
    if (expectedMaxSizeMetadataValue != null) {
        maxSizeMetadata.put("max_length_allowed", expectedMaxSizeMetadataValue);
    }
    return new ApiErrorWithMetadata(base, maxSizeMetadata);
}
 
Example #29
Source File: BackstopperRiposteFrameworkErrorHandlerListener.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Inject
public BackstopperRiposteFrameworkErrorHandlerListener(@NotNull ProjectApiErrors projectApiErrors) {
    //noinspection ConstantConditions
    if (projectApiErrors == null)
        throw new IllegalArgumentException("ProjectApiErrors cannot be null");

    this.projectApiErrors = projectApiErrors;

    CIRCUIT_BREAKER_GENERIC_API_ERROR =
        new ApiErrorBase(projectApiErrors.getTemporaryServiceProblemApiError(), "CIRCUIT_BREAKER");
    CIRCUIT_BREAKER_OPEN_API_ERROR =
        new ApiErrorBase(projectApiErrors.getTemporaryServiceProblemApiError(), "CIRCUIT_BREAKER_OPEN");
    CIRCUIT_BREAKER_TIMEOUT_API_ERROR =
        new ApiErrorBase(projectApiErrors.getTemporaryServiceProblemApiError(), "CIRCUIT_BREAKER_TIMEOUT");

    ApiError malformedReqError = projectApiErrors.getMalformedRequestApiError();
    // Too long line can keep generic malformed request ApiError error code, message, and HTTP status code (400),
    //      but we'll give it a new name for the logs and some cause metadata so the caller knows what went wrong.
    TOO_LONG_FRAME_LINE_API_ERROR_BASE = new ApiErrorWithMetadata(
        new ApiErrorBase(malformedReqError, "TOO_LONG_HTTP_LINE"),
        Pair.of("cause", TOO_LONG_FRAME_LINE_METADATA_MESSAGE)
    );
    // Too long headers should keep the error code and message of malformed request ApiError, but use 431 HTTP
    //      status code (see https://tools.ietf.org/html/rfc6585#page-4), and we'll give it a new name for the logs
    //      and some cause metadata so the caller knows what went wrong.
    TOO_LONG_FRAME_HEADER_API_ERROR_BASE = new ApiErrorWithMetadata(
        new ApiErrorBase(
            "TOO_LONG_HEADERS", malformedReqError.getErrorCode(), malformedReqError.getMessage(),
            431, malformedReqError.getMetadata()
        ),
        Pair.of("cause", TOO_LONG_FRAME_HEADER_METADATA_MESSAGE)
    );
}
 
Example #30
Source File: ConventionBasedSpringValidationErrorToApiErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleException_handles_WebExchangeBindException_as_expected() {
    // given
    BindingResult bindingResult = mock(BindingResult.class);

    ApiError someFieldError = testProjectApiErrors.getMissingExpectedContentApiError();
    ApiError otherFieldError = testProjectApiErrors.getTypeConversionApiError();
    ApiError notAFieldError = testProjectApiErrors.getGenericBadRequestApiError();
    List<ObjectError> errorsList = Arrays.asList(
        new FieldError("someObj", "someField", someFieldError.getName()),
        new FieldError("otherObj", "otherField", otherFieldError.getName()),
        new ObjectError("notAFieldObject", notAFieldError.getName())
    );
    when(bindingResult.getAllErrors()).thenReturn(errorsList);

    WebExchangeBindException ex = new WebExchangeBindException(null, bindingResult);

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    validateResponse(result, true, Arrays.asList(
        new ApiErrorWithMetadata(someFieldError, Pair.of("field", "someField")),
        new ApiErrorWithMetadata(otherFieldError, Pair.of("field", "otherField")),
        notAFieldError
    ));
    verify(bindingResult).getAllErrors();
}