org.zalando.problem.Problem Java Examples

The following examples show how to use org.zalando.problem.Problem. 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: ExceptionTranslator.java    From e-commerce-microservice with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example #2
Source File: EventTypeControllerTest.java    From nakadi with MIT License 6 votes vote down vote up
@Test
public void whenTimelineCreationFailsRemoveEventTypeFromRepositoryAnd500() throws Exception {

    final EventType et = TestUtils.buildDefaultEventType();
    doThrow(TopicCreationException.class).when(timelineService)
            .createDefaultTimeline(any(), anyInt());
    when(eventTypeRepository.saveEventType(any())).thenReturn(et);
    final Problem expectedProblem = Problem.valueOf(SERVICE_UNAVAILABLE);

    postEventType(et).andExpect(status().isServiceUnavailable())
            .andExpect(content().contentType("application/problem+json")).andExpect(content().string(
            matchesProblem(expectedProblem)));

    verify(eventTypeRepository, times(1)).saveEventType(any(EventType.class));
    verify(timelineService, times(1)).createDefaultTimeline(any(), anyInt());
    verify(eventTypeRepository, times(1)).removeEventType(et.getName());
}
 
Example #3
Source File: ExceptionTranslator.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example #4
Source File: ExceptionTranslator.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example #5
Source File: MethodNotAllowedAdviceTrait.java    From problem-spring-web with MIT License 6 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default Mono<ResponseEntity<Problem>> handleRequestMethodNotSupportedException(
        final MethodNotAllowedException exception,
        final ServerWebExchange request) {

    final Set<HttpMethod> methods = exception.getSupportedMethods();

    if (methods.isEmpty()) {
        return create(Status.METHOD_NOT_ALLOWED, exception, request);
    }

    final HttpHeaders headers = new HttpHeaders();
    headers.setAllow(methods);

    return create(Status.METHOD_NOT_ALLOWED, exception, request, headers);
}
 
Example #6
Source File: ExceptionTranslator.java    From ehcache3-samples with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with("message", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example #7
Source File: ExceptionTranslator.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example #8
Source File: ExceptionTranslator.java    From jhipster-registry with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
    BindingResult result = ex.getBindingResult();
    List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
        .map(f -> new FieldErrorVM(f.getObjectName().replaceFirst("DTO$", ""), f.getField(), f.getCode()))
        .collect(Collectors.toList());

    Problem problem = Problem.builder()
        .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
        .withTitle("Method argument not valid")
        .withStatus(defaultConstraintViolationStatus())
        .with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
        .with(FIELD_ERRORS_KEY, fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
Example #9
Source File: StoragesExceptionHandler.java    From nakadi with MIT License 5 votes vote down vote up
@ExceptionHandler(NoSuchStorageException.class)
public ResponseEntity<Problem> handleNoSuchStorageException(
        final NoSuchStorageException exception,
        final NativeWebRequest request) {
    AdviceTrait.LOG.debug(exception.getMessage());
    return create(Problem.valueOf(NOT_FOUND, exception.getMessage()), request);
}
 
Example #10
Source File: AdviceTraitsTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void fallsbackProblemWithStatus() {
    ResponseEntity<Problem> result = AdviceTraits.fallback(
            Problem.valueOf(Status.RESET_CONTENT),
            new HttpHeaders()
    );
    assertThat(result.getStatusCode(), is(HttpStatus.RESET_CONTENT));
    HttpHeaders expectedHeaders = new HttpHeaders();
    expectedHeaders.setContentType(MediaType.valueOf("application/problem+json"));
    assertThat(result.getHeaders(), is(expectedHeaders));
    assertThat(result.getBody().getStatus(), is(Status.RESET_CONTENT));
}
 
Example #11
Source File: AdviceTraitTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void buildsOnThrowableWithStatus() {
    final Problem result = unit.toProblem(new IllegalStateException("Message"), Status.RESET_CONTENT);

    assertThat(result.getStatus().getStatusCode(), is(205));
    assertThat(result.getType().toString(), is("about:blank"));
    assertThat(result.getTitle(), is("Reset Content"));
    assertThat(result.getDetail(), is("Message"));
}
 
Example #12
Source File: ExceptionTranslator.java    From e-commerce-microservice with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler
public ResponseEntity<Problem> handleNoSuchElementException(NoSuchElementException ex, NativeWebRequest request) {
    Problem problem = Problem.builder()
        .withStatus(Status.NOT_FOUND)
        .with("message", ErrorConstants.ENTITY_NOT_FOUND_TYPE)
        .build();
    return create(ex, problem, request);
}
 
Example #13
Source File: EventTypeControllerTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenPUTNotExistingEventTypeThen404() throws Exception {
    final EventType eventType = TestUtils.buildDefaultEventType();

    final Problem expectedProblem = Problem.valueOf(NOT_FOUND);

    doThrow(NoSuchEventTypeException.class).when(eventTypeRepository).findByName(eventType.getName());

    putEventType(eventType, eventType.getName()).andExpect(status().isNotFound())
            .andExpect(content().contentType("application/problem+json"))
            .andExpect(content().string(matchesProblem(expectedProblem)));
}
 
Example #14
Source File: ExceptionTranslator.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
@ExceptionHandler
public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) {
    Problem problem = Problem.builder()
        .withStatus(Status.CONFLICT)
        .with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE)
        .build();
    return create(ex, problem, request);
}
 
Example #15
Source File: EventTypeExceptionHandler.java    From nakadi with MIT License 5 votes vote down vote up
@ExceptionHandler({InvalidEventTypeException.class,
        UnableProcessException.class,
        EventTypeOptionsValidationException.class,
        AuthorizationSectionException.class,
        NoSuchPartitionStrategyException.class})
public ResponseEntity<Problem> handleUnprocessableEntityResponses(final NakadiBaseException exception,
                                                                  final NativeWebRequest request) {
    AdviceTrait.LOG.debug(exception.getMessage());
    return create(Problem.valueOf(UNPROCESSABLE_ENTITY, exception.getMessage()), request);
}
 
Example #16
Source File: UnsupportedMediaTypeAdviceTrait.java    From problem-spring-web with MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default Mono<ResponseEntity<Problem>> handleMediaTypeNotSupportedException(
        final UnsupportedMediaTypeStatusException exception,
        final ServerWebExchange request) {

    final HttpHeaders headers = new HttpHeaders();
    headers.setAccept(exception.getSupportedMediaTypes());

    return create(Status.UNSUPPORTED_MEDIA_TYPE, exception, request, headers);
}
 
Example #17
Source File: SubscriptionStreamController.java    From nakadi with MIT License 5 votes vote down vote up
private StreamingResponseBody stream(final String subscriptionId,
                                     final HttpServletRequest request,
                                     final HttpServletResponse response,
                                     final Client client,
                                     final StreamParameters streamParameters,
                                     final Span parentSubscriptionSpan) {
    final String flowId = FlowIdUtils.peek();

    return outputStream -> {
        FlowIdUtils.push(flowId);
        final String metricName = metricNameForSubscription(subscriptionId, CONSUMERS_COUNT_METRIC_NAME);
        final Counter consumerCounter = metricRegistry.counter(metricName);
        consumerCounter.inc();
        final AtomicBoolean connectionReady = closedConnectionsCrutch.listenForConnectionClose(request);
        SubscriptionStreamer streamer = null;
        final SubscriptionOutputImpl output = new SubscriptionOutputImpl(response, outputStream);
        try {
            if (eventStreamChecks.isSubscriptionConsumptionBlocked(subscriptionId, client.getClientId())) {
                writeProblemResponse(response, outputStream,
                        Problem.valueOf(FORBIDDEN, "Application or event type is blocked"));
                return;
            }
            final Subscription subscription = subscriptionDbRepository.getSubscription(subscriptionId);
            subscriptionValidationService.validatePartitionsToStream(subscription,
                    streamParameters.getPartitions());
            streamer = subscriptionStreamerFactory.build(subscription, streamParameters, output,
                    connectionReady, parentSubscriptionSpan, client.getClientId());
            streamer.stream();
        } catch (final InterruptedException ex) {
            LOG.warn("Interrupted while streaming with " + streamer, ex);
            Thread.currentThread().interrupt();
        } catch (final RuntimeException e) {
            output.onException(e);
        } finally {
            consumerCounter.dec();
            outputStream.close();
        }
    };
}
 
Example #18
Source File: CursorsControllerTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenServiceUnavailableExceptionThenServiceUnavailable() throws Exception {
    when(cursorsService.commitCursors(any(), any(), any(), any()))
            .thenThrow(new ServiceTemporarilyUnavailableException("dummy-message"));
    final Problem expectedProblem = Problem.valueOf(SERVICE_UNAVAILABLE, "dummy-message");

    checkForProblem(postCursors(DUMMY_CURSORS), expectedProblem);
}
 
Example #19
Source File: BindAdviceTrait.java    From problem-spring-web with MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default ResponseEntity<Problem> handleBindingResult(
        final BindException exception,
        final NativeWebRequest request) {
    return newConstraintViolationProblem(exception, createViolations(exception), request);
}
 
Example #20
Source File: ExceptionTranslator.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler
public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) {
    Problem problem = Problem.builder()
        .withStatus(Status.CONFLICT)
        .with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE)
        .build();
    return create(ex, problem, request);
}
 
Example #21
Source File: StoragesExceptionHandler.java    From nakadi with MIT License 5 votes vote down vote up
@ExceptionHandler(StorageIsUsedException.class)
public ResponseEntity<Problem> handleStorageIsUsedException(
        final StorageIsUsedException exception,
        final NativeWebRequest request) {
    AdviceTrait.LOG.debug(exception.getMessage());
    return create(Problem.valueOf(FORBIDDEN, exception.getMessage()), request);
}
 
Example #22
Source File: FallbackTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Override
public ResponseEntity<Problem> fallback(final Throwable throwable, final Problem problem,
        final NativeWebRequest request, final HttpHeaders headers) {
    return ResponseEntity
            .status(problem.getStatus().getStatusCode())
            .contentType(MediaType.TEXT_XML)
            .header("X-Fallback-Used", Boolean.toString(true))
            .body(null);
}
 
Example #23
Source File: EventTypeAuthorizationTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenPUTUnlimitedRetentionTimeByUserThen422() throws Exception {
    final EventTypeOptions eto = new EventTypeOptions();
    eto.setRetentionTime(Long.MAX_VALUE);
    final EventType eventType = EventTypeTestBuilder.builder().options(eto).build();

    doReturn(eventType).when(eventTypeRepository).findByName(any());
    when(adminService.isAdmin(AuthorizationService.Operation.WRITE)).thenReturn(false);

    putEventType(eventType, eventType.getName())
            .andExpect(status().isUnprocessableEntity())
            .andExpect(content().string(matchesProblem(Problem.valueOf(UNPROCESSABLE_ENTITY,
                    "Field \"options.retention_time\" can not be more than 345600000"))));
}
 
Example #24
Source File: MissingServletRequestPartAdviceTrait.java    From problem-spring-web with MIT License 5 votes vote down vote up
@API(status = INTERNAL)
@ExceptionHandler
default ResponseEntity<Problem> handleMissingServletRequestPart(
        final MissingServletRequestPartException exception,
        final NativeWebRequest request) {
    return create(Status.BAD_REQUEST, exception, request);
}
 
Example #25
Source File: ExceptionTranslator.java    From 21-points with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler
public ResponseEntity<Problem> handleConcurrencyFailure(ConcurrencyFailureException ex, NativeWebRequest request) {
    Problem problem = Problem.builder()
        .withStatus(Status.CONFLICT)
        .with("message", ErrorConstants.ERR_CONCURRENCY_FAILURE)
        .build();
    return create(ex, problem, request);
}
 
Example #26
Source File: SubscriptionControllerTest.java    From nakadi with MIT License 5 votes vote down vote up
@Test
public void whenGetSubscriptionAndExceptionThenServiceUnavailable() throws Exception {
    when(subscriptionRepository.getSubscription(any()))
            .thenThrow(new ServiceTemporarilyUnavailableException("dummy message"));
    final Problem expectedProblem = Problem.valueOf(SERVICE_UNAVAILABLE, "dummy message");
    checkForProblem(getSubscription("dummyId"), expectedProblem);
}
 
Example #27
Source File: NakadiProblemExceptionHandler.java    From nakadi with MIT License 5 votes vote down vote up
@Override
@ExceptionHandler
public ResponseEntity<Problem> handleThrowable(final Throwable throwable, final NativeWebRequest request) {
    final String errorTraceId = generateErrorTraceId();
    LOG.error("InternalServerError (" + errorTraceId + "):", throwable);
    return create(Problem.valueOf(INTERNAL_SERVER_ERROR, "An internal error happened. Please report it. ("
            + errorTraceId + ")"), request);
}
 
Example #28
Source File: ExceptionTranslator.java    From cubeai with Apache License 2.0 5 votes vote down vote up
/**
 * Post-process Problem payload to add the message key for front-end if needed
 */
@Override
public ResponseEntity<Problem> process(@Nullable ResponseEntity<Problem> entity, NativeWebRequest request) {
    if (entity == null || entity.getBody() == null) {
        return entity;
    }
    Problem problem = entity.getBody();
    if (!(problem instanceof ConstraintViolationProblem || problem instanceof DefaultProblem)) {
        return entity;
    }
    ProblemBuilder builder = Problem.builder()
        .withType(Problem.DEFAULT_TYPE.equals(problem.getType()) ? ErrorConstants.DEFAULT_TYPE : problem.getType())
        .withStatus(problem.getStatus())
        .withTitle(problem.getTitle())
        .with("path", request.getNativeRequest(HttpServletRequest.class).getRequestURI());

    if (problem instanceof ConstraintViolationProblem) {
        builder
            .with("violations", ((ConstraintViolationProblem) problem).getViolations())
            .with("message", ErrorConstants.ERR_VALIDATION);
        return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
    } else {
        builder
            .withCause(((DefaultProblem) problem).getCause())
            .withDetail(problem.getDetail())
            .withInstance(problem.getInstance());
        problem.getParameters().forEach(builder::with);
        if (!problem.getParameters().containsKey("message") && problem.getStatus() != null) {
            builder.with("message", "error.http." + problem.getStatus().getStatusCode());
        }
        return new ResponseEntity<>(builder.build(), entity.getHeaders(), entity.getStatusCode());
    }
}
 
Example #29
Source File: AdviceTraitTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void buildsOnThrowable() {
    final ResponseEntity<Problem> result = unit.create(Status.RESET_CONTENT,
            new IllegalStateException("Message"), request()).block();

    assertThat(result, hasFeature("Status", ResponseEntity::getStatusCode, is(RESET_CONTENT)));
    assertThat(result.getHeaders(), hasFeature("Content-Type", HttpHeaders::getContentType, is(PROBLEM)));
    assertThat(result.getBody(), compose(hasFeature("Status", Problem::getStatus, is(Status.RESET_CONTENT)))
            .and(hasFeature("Detail", Problem::getDetail, is("Message"))));
}
 
Example #30
Source File: AdviceTraits.java    From problem-spring-web with MIT License 5 votes vote down vote up
public static ResponseEntity<Problem> fallback(
        final Problem problem,
        final HttpHeaders headers) {
    return ResponseEntity
            .status(HttpStatus.valueOf(Optional.ofNullable(problem.getStatus())
                    .orElse(Status.INTERNAL_SERVER_ERROR)
                    .getStatusCode()))
            .headers(headers)
            .contentType(PROBLEM)
            .body(problem);
}