Java Code Examples for com.nike.backstopper.apierror.ApiError

The following examples show how to use com.nike.backstopper.apierror.ApiError. These examples are extracted from open source projects. 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 Project: riposte   Source File: ServerConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return The error handler that should be used for this application for handling known errors. For things that
 * fall through the cracks they will be handled by {@link #riposteUnhandledErrorHandler()}.
 *
 * <p>NOTE: The default implementation returned if you don't override this method is a very basic Backstopper impl -
 * it will not know about your application's {@link ProjectApiErrors} and will instead create a dummy {@link
 * ProjectApiErrors} that only supports the {@link com.nike.backstopper.apierror.sample.SampleCoreApiError} values.
 * This method should be overridden for most real applications to return a real implementation tailored for your
 * app. In practice this usually means copy/pasting this method and simply supplying the correct {@link
 * ProjectApiErrors} for the app. The rest is usually fine for defaults.
 */
default @NotNull RiposteErrorHandler riposteErrorHandler() {
    ProjectApiErrors projectApiErrors = new SampleProjectApiErrorsBase() {
        @Override
        protected List<ApiError> getProjectSpecificApiErrors() {
            return null;
        }

        @Override
        protected ProjectSpecificErrorCodeRange getProjectSpecificErrorCodeRange() {
            return null;
        }
    };
    return BackstopperRiposteConfigHelper
        .defaultErrorHandler(projectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL);
}
 
Example 2
Source Project: backstopper   Source File: ApiExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false",
}, splitBy = "\\|")
@Test(expected = IllegalArgumentException.class)
public void with_cause_constructors_fail_when_passed_null_or_empty_apiErrors_list(
    boolean useNull, boolean useConstructorWithResponseHeaders
) {
    // given
    List<Pair<String, String>> logInfoList = Collections.emptyList();
    List<Pair<String, List<String>>> responseHeaders = Collections.emptyList();
    List<ApiError> apiErrors = (useNull) ? null : Collections.<ApiError>emptyList();

    // expect
    if (useConstructorWithResponseHeaders)
        new ApiException(apiErrors, logInfoList, responseHeaders, exceptionMessage, cause);
    else
        new ApiException(apiErrors, logInfoList, exceptionMessage, cause);
}
 
Example 3
@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 4
Source Project: backstopper   Source File: SanityCheckComponentTest.java    License: Apache License 2.0 6 votes vote down vote up
private void verifyErrorReceived(ExtractableResponse response, Collection<ApiError> expectedErrors, int expectedHttpStatusCode) {
    assertThat(response.statusCode()).isEqualTo(expectedHttpStatusCode);
    try {
        DefaultErrorContractDTO errorContract = objectMapper.readValue(response.asString(), DefaultErrorContractDTO.class);
        assertThat(errorContract.error_id).isNotEmpty();
        assertThat(UUID.fromString(errorContract.error_id)).isNotNull();
        assertThat(errorContract.errors).hasSameSizeAs(expectedErrors);
        for (ApiError apiError : expectedErrors) {
            DefaultErrorDTO matchingError = findErrorMatching(errorContract, apiError);
            assertThat(matchingError).isNotNull();
            assertThat(matchingError.code).isEqualTo(apiError.getErrorCode());
            assertThat(matchingError.message).isEqualTo(apiError.getMessage());
            assertThat(matchingError.metadata).isEqualTo(apiError.getMetadata());
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
@Test
public void generateLastDitchFallbackErrorResponseInfo_returns_expected_value() {
    // given
    Exception ex = new Exception("kaboom");
    RequestInfoForLogging reqMock = mock(RequestInfoForLogging.class);
    String errorId = UUID.randomUUID().toString();
    Map<String, List<String>> headersMap = MapBuilder.builder("error_uid", singletonList(errorId)).build();

    ApiError expectedGenericError = testProjectApiErrors.getGenericServiceError();
    int expectedHttpStatusCode = expectedGenericError.getHttpStatusCode();
    Map<String, List<String>> expectedHeadersMap = new HashMap<>(headersMap);
    String expectedBodyPayload = JsonUtilWithDefaultErrorContractDTOSupport.writeValueAsString(
        new DefaultErrorContractDTO(errorId, singletonList(expectedGenericError))
    );

    // when
    ErrorResponseInfo<Response.ResponseBuilder> response = handler.generateLastDitchFallbackErrorResponseInfo(ex, reqMock, errorId, headersMap);

    // then
    assertThat(response.httpStatusCode).isEqualTo(expectedHttpStatusCode);
    assertThat(response.headersToAddToResponse).isEqualTo(expectedHeadersMap);
    Response builtFrameworkResponse = response.frameworkRepresentationObj.build();
    assertThat(builtFrameworkResponse.getStatus()).isEqualTo(expectedHttpStatusCode);
    assertThat(builtFrameworkResponse.getEntity()).isEqualTo(expectedBodyPayload);
}
 
Example 6
Source Project: backstopper   Source File: ApiExceptionHandlerUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return Helper method for turning the given collection into a comma-delimited string of
 *          {@link ApiError#getName()}. Will return blank string (not null) if you pass in null or an empty
 *          collection.
 */
public String concatenateErrorCollection(Collection<ApiError> errors) {
    if (errors == null || errors.isEmpty())
        return "";

    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (ApiError error : errors) {
        if (!first)
            sb.append(',');
        sb.append(error.getName());
        first = false;
    }

    return sb.toString();
}
 
Example 7
Source Project: backstopper   Source File: ProjectApiErrorsTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_contain_same_error_codes_for_different_instances_that_are_not_wrappers() {
    Set<String> allowedDuplicateErrorCodes = allowedDuplicateErrorCodes();
    Map<String, ApiError> codeToErrorMap = new HashMap<>();
    for (ApiError apiError : getProjectApiErrors().getProjectApiErrors()) {
        ApiError errorWithSameCode = codeToErrorMap.get(apiError.getErrorCode());

        if (errorWithSameCode != null && !areWrappersOfEachOther(apiError, errorWithSameCode)
            && !allowedDuplicateErrorCodes.contains(apiError.getErrorCode()))
        {
            throw new AssertionError(
                "There are ApiError instances in the ProjectApiErrors that share duplicate error codes and are not "
                + "wrappers of each other. error_code=" + apiError.getErrorCode() + ", conflicting_api_errors=["
                + apiError.getName() + ", " + errorWithSameCode.getName() + "]"
            );
        }

        codeToErrorMap.put(apiError.getErrorCode(), apiError);
    }
}
 
Example 8
Source Project: riposte   Source File: ServerConfig.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @return The error handler that should be used for this application for handling unknown/unexpected/unhandled
 * errors. Known/handled errors will be processed by {@link #riposteErrorHandler()}.
 *
 * <p>NOTE: The default implementation returned if you don't override this method is a very basic Backstopper impl -
 * it will not know about your application's {@link ProjectApiErrors} and will instead create a dummy {@link
 * ProjectApiErrors} that only supports the {@link com.nike.backstopper.apierror.sample.SampleCoreApiError} values.
 * This method should be overridden for most real applications to return a real implementation tailored for your
 * app. In practice this usually means copy/pasting this method and simply supplying the correct {@link
 * ProjectApiErrors} for the app. The rest is usually fine for defaults.
 */
default @NotNull RiposteUnhandledErrorHandler riposteUnhandledErrorHandler() {
    ProjectApiErrors projectApiErrors = new SampleProjectApiErrorsBase() {
        @Override
        protected List<ApiError> getProjectSpecificApiErrors() {
            return null;
        }

        @Override
        protected ProjectSpecificErrorCodeRange getProjectSpecificErrorCodeRange() {
            return null;
        }
    };
    return BackstopperRiposteConfigHelper
        .defaultUnhandledErrorHandler(projectApiErrors, ApiExceptionHandlerUtils.DEFAULT_IMPL);
}
 
Example 9
@Test
public void handleException_should_not_allow_error_uid_from_extraHeadersForResponse_to_override_true_error_uid() {
    // given
    final Map<String, List<String>> baseExtraHeaders = MapBuilder
        .builder("error_uid", singletonList(UUID.randomUUID().toString()))
        .build();
    UnhandledExceptionHandlerBase<TestDTO> handler = new TestUnhandledExceptionHandler(testProjectApiErrors, utilsSpy) {
        @Override
        protected Map<String, List<String>> extraHeadersForResponse(TestDTO frameworkRepresentation, DefaultErrorContractDTO errorContractDTO,
                                                                    int httpStatusCode, Collection<ApiError> rawFilteredApiErrors,
                                                                    Throwable originalException,
                                                                    RequestInfoForLogging request) {
            return baseExtraHeaders;
        }
    };

    // when
    ErrorResponseInfo<TestDTO> result = handler.handleException(new Exception(), reqMock);

    // then
    assertThat(result.headersToAddToResponse.get("error_uid"))
              .isNotEqualTo(baseExtraHeaders.get("error_uid"))
              .isEqualTo(singletonList(result.frameworkRepresentationObj.erv.error_id));
}
 
Example 10
Source Project: backstopper   Source File: ApiExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true   |   true",
    "true   |   false",
    "false  |   true",
    "false  |   false",
}, splitBy = "\\|")
@Test(expected = IllegalArgumentException.class)
public void no_cause_constructors_fail_when_passed_null_or_empty_apiErrors_list(
    boolean useNull, boolean useConstructorWithResponseHeaders
) {
    // given
    List<Pair<String, String>> logInfoList = Collections.emptyList();
    List<Pair<String, List<String>>> responseHeaders = Collections.emptyList();
    List<ApiError> apiErrors = (useNull) ? null : Collections.<ApiError>emptyList();

    // expect
    if (useConstructorWithResponseHeaders)
        new ApiException(apiErrors, logInfoList, responseHeaders, exceptionMessage);
    else
        new ApiException(apiErrors, logInfoList, exceptionMessage);
}
 
Example 11
Source Project: backstopper   Source File: ProjectApiErrorsTestBaseTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void verifyGetStatusCodePriorityOrderMethodContainsAllRelevantCodes_throws_AssertionError_if_it_finds_bad_state() {
    // given
    final ProjectApiErrorsTestBase base = new ProjectApiErrorsTestBase() {
        @Override
        protected ProjectApiErrors getProjectApiErrors() {
            return ProjectApiErrorsForTesting.withProjectSpecificData(Arrays.<ApiError>asList(
                new ApiErrorBase("FOOBAR", 42, "foo", 123456)
            ), ProjectSpecificErrorCodeRange.ALLOW_ALL_ERROR_CODES);
        }
    };

    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            base.verifyGetStatusCodePriorityOrderMethodContainsAllRelevantCodes();
        }
    });

    // then
    assertThat(ex)
        .isInstanceOf(AssertionError.class)
        .hasMessageContaining("getStatusCodePriorityOrder() did not contain HTTP Status Code: 123456");
}
 
Example 12
private void verifyErrors(ApiExceptionHandlerListenerResult val, SortedApiErrorSet expectedErrors) {
    if (expectedErrors == null) {
        assertThat(val.errors)
            .isNotNull()
            .isEmpty();
    }
    else {
        assertThat(val.errors).isEqualTo(expectedErrors);
    }

    // verify mutability
    ApiError newError = new ApiErrorBase(UUID.randomUUID().toString(), "foo", "bar", 400);
    // and when
    val.errors.add(newError);
    // then
    assertThat(val.errors).contains(newError);
}
 
Example 13
/**
 * Method for generating a {@link Mono} of {@link ServerResponse} that contains a serialized representation of the
 * given {@link DefaultErrorContractDTO} as its body (JSON serialization by default).
 *
 * <p>NOTE: make sure the {@link DefaultErrorContractDTO} is FULLY populated before calling this method! Changes to
 * the {@link DefaultErrorContractDTO} after calling this method may not be reflected in the
 * returned {@code Mono<ServerResponse>}.
 *
 * <p>The following two methods control the serialized representation of the error contract that will be used
 * as the {@link ServerResponse}'s body: {@link #serializeErrorContractToString(DefaultErrorContractDTO)} and
 * {@link #getErrorResponseContentType(DefaultErrorContractDTO, int, Collection, Throwable, RequestInfoForLogging)}.
 *
 * @return A {@link Mono} of {@link ServerResponse} that contains a serialized representation of the given
 * {@link DefaultErrorContractDTO}.
 */
public Mono<ServerResponse> generateServerResponseForError(
    DefaultErrorContractDTO errorContractDTO,
    int httpStatusCode,
    Collection<ApiError> rawFilteredApiErrors,
    Throwable originalException,
    RequestInfoForLogging request
) {
    return ServerResponse
        .status(httpStatusCode)
        .contentType(
            getErrorResponseContentType(
                errorContractDTO, httpStatusCode, rawFilteredApiErrors, originalException, request
            )
        )
        .syncBody(serializeErrorContractToString(errorContractDTO));
}
 
Example 14
@Test
public void prepareFrameworkRepresentation_delegates_to_SpringWebfluxApiExceptionHandlerUtils() {
    // given
    Mono<ServerResponse> expectedResult = mock(Mono.class);

    DefaultErrorContractDTO errorContractDTOMock = mock(DefaultErrorContractDTO.class);
    int httpStatusCode = 400;
    Collection<ApiError> rawFilteredApiErrors = mock(Collection.class);
    Throwable originalException = mock(Throwable.class);
    RequestInfoForLogging request = mock(RequestInfoForLogging.class);

    doReturn(expectedResult).when(springUtilsMock).generateServerResponseForError(
        errorContractDTOMock, httpStatusCode, rawFilteredApiErrors, originalException, request
    );

    // when
    Mono<ServerResponse> result = handlerSpy.prepareFrameworkRepresentation(
        errorContractDTOMock, httpStatusCode, rawFilteredApiErrors, originalException, request
    );

    // then
    assertThat(result).isSameAs(expectedResult);
    verify(springUtilsMock).generateServerResponseForError(
        errorContractDTOMock, httpStatusCode, rawFilteredApiErrors, originalException, request
    );
}
 
Example 15
@Test
public void getErrorResponseContentType_returns_APPLICATION_JSON_UTF8_by_default() {
    // given
    DefaultErrorContractDTO errorContractDtoMock = mock(DefaultErrorContractDTO.class);
    int statusCode = 400;
    Collection<ApiError> errors = mock(Collection.class);
    Throwable ex = mock(Throwable.class);
    RequestInfoForLogging requestMock = mock(RequestInfoForLogging.class);

    // when
    MediaType result = utilsSpy.getErrorResponseContentType(
        errorContractDtoMock, statusCode, errors, ex, requestMock
    );

    // then
    assertThat(result).isEqualTo(MediaType.APPLICATION_JSON_UTF8);
    verifyZeroInteractions(errorContractDtoMock, errors, ex, requestMock);
}
 
Example 16
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void handleResponse_one_arg_should_work_as_expected(boolean useNull) {
    // given
    SortedApiErrorSet errors = (useNull) ? null : new SortedApiErrorSet(Arrays.<ApiError>asList(
        BarebonesCoreApiErrorForTesting.GENERIC_SERVICE_ERROR, BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST
    ));

    // when
    ApiExceptionHandlerListenerResult val = ApiExceptionHandlerListenerResult.handleResponse(errors);

    // then
    verifyErrors(val, errors);
}
 
Example 17
@Test
public void shouldReturnExpectedErrorsForViolationsThatMapToApiErrors() {
    ConstraintViolation<Object> violation1 = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation1", NotNull.class, "MISSING_EXPECTED_CONTENT");
    ConstraintViolation<Object> violation2 = setupConstraintViolation(SomeValidatableObject.class, "path.to.violation2", NotEmpty.class, "TYPE_CONVERSION_ERROR");
    ClientDataValidationError ex = new ClientDataValidationError(
        Collections.<Object>singletonList(new SomeValidatableObject("someArg1", "someArg2")), Arrays.asList(violation1, violation2), null);
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);
    validateResponse(result, true, Arrays.<ApiError>asList(
        // We expect them to be the properly associated errors, with some metadata about the field that had an issue
        new ApiErrorWithMetadata(BarebonesCoreApiErrorForTesting.MISSING_EXPECTED_CONTENT, Pair.of("field", (Object)"path.to.violation1")),
        new ApiErrorWithMetadata(BarebonesCoreApiErrorForTesting.TYPE_CONVERSION_ERROR, Pair.of("field", (Object)"path.to.violation2"))
    ));
}
 
Example 18
@Before
public void beforeMethod() {
      instanceSpy = spy(new ApiExceptionHandlerServletApiBase<Object>(mock(ProjectApiErrors.class),
                                                                      Collections.<ApiExceptionHandlerListener>emptyList(),
                                                                      ApiExceptionHandlerUtils.DEFAULT_IMPL) {
          @Override
          protected Object prepareFrameworkRepresentation(DefaultErrorContractDTO errorContractDTO, int httpStatusCode, Collection<ApiError> filteredClientErrors,
                                                          Throwable originalException, RequestInfoForLogging request) {
              return null;
          }
      });
    servletRequestMock = mock(HttpServletRequest.class);
    servletResponseMock = mock(HttpServletResponse.class);
}
 
Example 19
Source Project: backstopper   Source File: ListenerTestBase.java    License: Apache License 2.0 5 votes vote down vote up
protected void validateResponse(ApiExceptionHandlerListenerResult result, boolean expectedShouldHandle, Collection<? extends ApiError> expectedErrors) {
    if (!expectedShouldHandle) {
        assertThat(result.shouldHandleResponse).isFalse();
        return;
    }

    assertThat(result.errors).containsExactlyInAnyOrderElementsOf(expectedErrors);
}
 
Example 20
Source Project: backstopper   Source File: ProjectApiErrorsTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void determineHighestPriorityHttpStatusCodeShouldReturnTheSameValueRegardlessOfErrorOrder() {
    List<ApiError> list = Arrays.asList(
        findRandomApiErrorWithHttpStatusCode(getProjectApiErrors().getStatusCodePriorityOrder()
                                                                  .get(0)),
        findRandomApiErrorWithHttpStatusCode(getProjectApiErrors().getStatusCodePriorityOrder()
                                                                  .get(1)));

    int returnValNormalOrder = getProjectApiErrors().determineHighestPriorityHttpStatusCode(list);
    Collections.reverse(list);

    int returnValReverseOrder = getProjectApiErrors().determineHighestPriorityHttpStatusCode(list);
    assertThat(returnValNormalOrder, is(returnValReverseOrder));
}
 
Example 21
Source Project: backstopper   Source File: DefaultErrorContractDTO.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given list of {@link ApiError}s into a list of {@link DefaultErrorDTO} objects.
 */
@SuppressWarnings("WeakerAccess")
protected static List<DefaultErrorDTO> convertApiErrorsToErrorModelObjects(Collection<ApiError> apiErrors) {
    if (apiErrors == null) {
        return null;
    }

    List<DefaultErrorDTO> errorsList = new ArrayList<>();
    for (ApiError apiError : apiErrors) {
        errorsList.add(new DefaultErrorDTO(apiError));
    }

    return errorsList;
}
 
Example 22
@Test
public void toResponseReturnsCorrectResponseForCoreApiErrorException() {

    ApiError expectedError = BarebonesCoreApiErrorForTesting.MALFORMED_REQUEST;
    ApiException.Builder exceptionBuilder = ApiException.Builder.newBuilder();
    exceptionBuilder.withExceptionMessage("test this");
    exceptionBuilder.withApiErrors(expectedError);
    Response actualResponse = handlerSpy.toResponse(exceptionBuilder.build());

    Assert.assertEquals(expectedError.getHttpStatusCode(), actualResponse.getStatus());
}
 
Example 23
@DataProvider(value = {
    "451",
    "506"
}, splitBy = "\\|")
@Test
public void verify_generic_ResponseStatusCode_exception_with_unknown_status_code_results_in_synthetic_ApiError(
    int unknownStatusCode
) {
    ExtractableResponse response =
        given()
            .baseUri("http://localhost")
            .port(SERVER_PORT)
            .log().all()
            .when()
            .header("desired-status-code", unknownStatusCode)
            .get(RESPONSE_STATUS_EX_FOR_SPECIFIC_STATUS_CODE_ENDPOINT)
            .then()
            .log().all()
            .extract();

    String expectedErrorCodeUsed = (unknownStatusCode >= 500)
                                   ? projectApiErrors.getGenericServiceError().getErrorCode()
                                   : projectApiErrors.getGenericBadRequestApiError().getErrorCode();

    ApiError expectedError = new ApiErrorBase(
        "GENERIC_API_ERROR_FOR_RESPONSE_STATUS_CODE_" + unknownStatusCode,
        expectedErrorCodeUsed,
        "An error occurred that resulted in response status code " + unknownStatusCode,
        unknownStatusCode
    );

    verifyErrorReceived(response, expectedError);
    ResponseStatusException ex = verifyResponseStatusExceptionSeenByBackstopper(
        ResponseStatusException.class, unknownStatusCode
    );
    verifyHandlingResult(
        expectedError,
        Pair.of("exception_message", quotesToApostrophes(ex.getMessage()))
    );
}
 
Example 24
Source Project: cerberus   Source File: OneLoginAuthConnector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AuthResponse triggerChallenge(String stateToken, String deviceId) {

  // TODO Convert to Default API Error once bug in Backstopper that doesn't allow 501 status codes
  // is fixed.
  throw ApiException.newBuilder()
      .withApiErrors(
          new ApiError() {
            @Override
            public String getName() {
              return "TRIGGER_CHALLENGE_NOT_IMPLEMENTED";
            }

            @Override
            public String getErrorCode() {
              return "99244";
            }

            @Override
            public String getMessage() {
              return "Call to trigger sms or call challenge for OneLogin is not implemented.";
            }

            @Override
            public Map<String, Object> getMetadata() {
              return null;
            }

            @Override
            public int getHttpStatusCode() {
              return 501;
            }
          })
      .withExceptionMessage(
          "Call to trigger sms or call challenge for OneLogin is not implemented.")
      .build();
}
 
Example 25
/**
 * @return Converts the given constraint violation to a {@link ApiError} if the constraint violation's
 *          {@link ConstraintViolation#getMessage()} can be converted via
 *          {@link ProjectApiErrors#convertToApiError(String, ApiError)}, otherwise falls back to
 *          {@link ProjectApiErrors#getGenericServiceError()}.
 */
protected ApiError convertValidationErrorToApiError(ConstraintViolation<Object> validationError) {
    String message = validationError.getMessage();
    Map<String, Object> errorMetadata = new HashMap<>();
    errorMetadata.put("field", validationError.getPropertyPath().toString());
    return new ApiErrorWithMetadata(
            projectApiErrors.convertToApiError(message, projectApiErrors.getGenericServiceError()),
            errorMetadata
    );
}
 
Example 26
@Override
protected Mono<ServerResponse> prepareFrameworkRepresentation(
    DefaultErrorContractDTO errorContractDTO,
    int httpStatusCode,
    Collection<ApiError> rawFilteredApiErrors,
    Throwable originalException,
    RequestInfoForLogging request
) {
    return springUtils.generateServerResponseForError(
        errorContractDTO, httpStatusCode, rawFilteredApiErrors, originalException, request
    );
}
 
Example 27
Source Project: riposte   Source File: ErrorResponseBodyImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void errorResponseViewWrapperConstructorWorks() {
    String errorUuid = UUID.randomUUID().toString();
    List<ApiError> errorsList = Arrays.asList(BarebonesCoreApiErrorForTesting.NO_ACCEPTABLE_REPRESENTATION, BarebonesCoreApiErrorForTesting.UNSUPPORTED_MEDIA_TYPE);
    DefaultErrorContractDTO errorContract = new DefaultErrorContractDTO(errorUuid, errorsList);
    ErrorResponseBodyImpl adapter = new ErrorResponseBodyImpl(errorContract);
    verifyAdapter(adapter, errorUuid, errorsList);
}
 
Example 28
private void verifyErrorReceived(ExtractableResponse response, ApiError expectedApiError) throws IOException {
    assertThat(response.statusCode()).isEqualTo(expectedApiError.getHttpStatusCode());
    DefaultErrorContractDTO responseAsError = objectMapper.readValue(response.asString(), DefaultErrorContractDTO.class);
    assertThat(responseAsError.errors).hasSize(1);
    assertThat(responseAsError.errors.get(0).code).isEqualTo(expectedApiError.getErrorCode());
    assertThat(responseAsError.errors.get(0).message).isEqualTo(expectedApiError.getMessage());
}
 
Example 29
Source Project: backstopper   Source File: ProjectApiErrorsTestBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotContainDuplicateNamedApiErrors_blows_up_if_it_finds_duplicate_ApiErrors() {
    // given
    final ProjectApiErrorsTestBase base = new ProjectApiErrorsTestBase() {
        @Override
        protected ProjectApiErrors getProjectApiErrors() {
            return ProjectApiErrorsForTesting.withProjectSpecificData(Arrays.<ApiError>asList(
                new ApiErrorBase("DUPNAME1", 42, "foo", 400),
                new ApiErrorBase("DUPNAME1", 4242, "bar", 500),
                new ApiErrorBase("DUPNAME2", 52, "foo2", 401),
                new ApiErrorBase("DUPNAME2", 5252, "bar2", 501),
                new ApiErrorBase("DUPNAME2", 525252, "baz", 900)
            ), ProjectSpecificErrorCodeRange.ALLOW_ALL_ERROR_CODES);
        }
    };

    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            base.shouldNotContainDuplicateNamedApiErrors();
        }
    });

    // then
    assertThat(ex)
        .isInstanceOf(AssertionError.class)
        .hasMessageContaining("[DUPNAME1, 2], [DUPNAME2, 3]");
}
 
Example 30
Source Project: riposte   Source File: ErrorResponseBodyImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void doubleArgConstructorWorks() {
    String errorUuid = UUID.randomUUID().toString();
    List<ApiError> errorsList = Arrays.asList(BarebonesCoreApiErrorForTesting.NO_ACCEPTABLE_REPRESENTATION, BarebonesCoreApiErrorForTesting.UNSUPPORTED_MEDIA_TYPE);
    ErrorResponseBodyImpl adapter = new ErrorResponseBodyImpl(errorUuid, errorsList);
    verifyAdapter(adapter, errorUuid, errorsList);
}