Java Code Examples for reactor.core.publisher.Mono#error()

The following examples show how to use reactor.core.publisher.Mono#error() . 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: ArmeriaClientHttpConnector.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<ClientHttpResponse> connect(
        HttpMethod method, URI uri, Function<? super ClientHttpRequest, Mono<Void>> requestCallback) {
    try {
        requireNonNull(method, "method");
        requireNonNull(uri, "uri");
        requireNonNull(requestCallback, "requestCallback");

        final ArmeriaClientHttpRequest request = createRequest(method, uri);
        return requestCallback.apply(request)
                              .then(Mono.fromFuture(request.future()))
                              .map(ArmeriaHttpClientResponseSubscriber::new)
                              .flatMap(s -> Mono.fromFuture(s.headersFuture())
                                                .map(headers -> createResponse(headers, s)));
    } catch (NullPointerException | IllegalArgumentException e) {
        return Mono.error(e);
    }
}
 
Example 2
Source File: RoutingServerRSocket.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> fireAndForget(Payload payload) {
  try {
    final MetadataDecoder.Metadata decodedMetadata = decoder.decode(payload.sliceMetadata());

    final String route = decodedMetadata.route();
    final IPCFunction<Mono<Void>> monoIPCFunction = this.router.routeFireAndForget(route);

    if (monoIPCFunction == null) {
      return Mono.error(new RouteNotFound("Nothing found for route " + route));
    }

    final Mono<Void> response = monoIPCFunction.apply(payload, decodedMetadata);

    payload.release();

    return response;
  } catch (Throwable t) {
    payload.release();
    return Mono.error(t);
  }
}
 
Example 3
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieSetInResponse() {
    final String token = "test_token";
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            ResponseCookie cookie = filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME);
            assertThat(cookie).isNotNull();
            assertThat(cookie.getName()).isEqualTo(CSRF_COOKIE_NAME);
            assertThat(cookie.getValue()).isEqualTo(token);
            assertThat(cookie.getPath()).isEqualTo("/");
            assertThat(cookie.getMaxAge()).isEqualTo(Duration.ofSeconds(-1));
            assertThat(cookie.isHttpOnly()).isFalse();
            assertThat(cookie.isSecure()).isFalse();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest.post(TEST_URL)
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", token)));
    this.filter.filter(exchange, filterChain).block();
}
 
Example 4
Source File: CookieCsrfFilterTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@Test
public void cookieNotSetIfTokenInRequest() {
    WebFilterChain filterChain = (filterExchange) -> {
        try {
            assertThat(filterExchange.getResponse().getCookies().getFirst(CSRF_COOKIE_NAME)).isNull();
        } catch (AssertionError ex) {
            return Mono.error(ex);
        }
        return Mono.empty();
    };
    MockServerWebExchange exchange = MockServerWebExchange.from(
        MockServerHttpRequest
            .post(TEST_URL)
            .cookie(new HttpCookie(CSRF_COOKIE_NAME, "csrf_token"))
    );
    exchange.getAttributes().put(CsrfToken.class.getName(), Mono.just(new DefaultCsrfToken(CSRF_COOKIE_NAME, "_csrf", "some token")));
    this.filter.filter(exchange, filterChain).block();
}
 
Example 5
Source File: ReactorClusterMembershipGrpcService.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
/**
 * Enable or disable a member.
 */
public Mono<ClusterMembershipRevision> enableMember(EnableMemberRequest request) {
    if (!request.getMemberId().equals(localMemberId)) {
        return Mono.error(ClusterMembershipServiceException.localOnly(request.getMemberId()));
    }
    return service.updateSelf(current ->
            com.netflix.titus.api.clustermembership.model.ClusterMembershipRevision.<ClusterMember>newBuilder()
                    .withCurrent(current.toBuilder()
                            .withEnabled(request.getEnabled())
                            .build()
                    )
                    .withCode(request.getEnabled() ? "enabled" : "disabled")
                    .withMessage("Changed enabled status to: " + request.getEnabled())
                    .withTimestamp(clock.wallTime())
                    .build()
    ).map(c -> toGrpcClusterMembershipRevision(c, isLocalLeader()));
}
 
Example 6
Source File: TestServiceInstanceBindingService.java    From spring-cloud-open-service-broker with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<DeleteServiceInstanceBindingResponse> deleteServiceInstanceBinding(
		DeleteServiceInstanceBindingRequest request) {
	if (IN_PROGRESS_SERVICE_INSTANCE_ID.equals(request.getServiceInstanceId())) {
		return Mono.error(new ServiceBrokerDeleteOperationInProgressException("task_10"));
	}
	if (UNKNOWN_SERVICE_INSTANCE_ID.equals(request.getServiceInstanceId())) {
		return Mono.error(new ServiceInstanceDoesNotExistException(request.getServiceInstanceId()));
	}
	if (UNKNOWN_BINDING_ID.equals(request.getBindingId())) {
		return Mono.error(new ServiceInstanceBindingDoesNotExistException(request.getBindingId()));
	}
	if (request.isAsyncAccepted()) {
		return Mono.just(DeleteServiceInstanceBindingResponse.builder()
				.async(true)
				.operation("working")
				.build());
	}
	else {
		return Mono.just(DeleteServiceInstanceBindingResponse.builder()
				.build());
	}
}
 
Example 7
Source File: DispatcherHandler.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Mono<HandlerResult> invokeHandler(ServerWebExchange exchange, Object handler) {
	if (this.handlerAdapters != null) {
		for (HandlerAdapter handlerAdapter : this.handlerAdapters) {
			if (handlerAdapter.supports(handler)) {
				return handlerAdapter.handle(exchange, handler);
			}
		}
	}
	return Mono.error(new IllegalStateException("No HandlerAdapter: " + handler));
}
 
Example 8
Source File: DaprClientGrpc.java    From java-sdk with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public <T> Mono<T> invokeBinding(
    String name, String operation, Object data, Map<String, String> metadata, Class<T> clazz) {
  try {
    if (name == null || name.trim().isEmpty()) {
      throw new IllegalArgumentException("Binding name cannot be null or empty.");
    }

    if (operation == null || operation.trim().isEmpty()) {
      throw new IllegalArgumentException("Binding operation cannot be null or empty.");
    }

    byte[] byteData = objectSerializer.serialize(data);
    DaprProtos.InvokeBindingRequest.Builder builder = DaprProtos.InvokeBindingRequest.newBuilder()
        .setName(name).setOperation(operation);
    if (byteData != null) {
      builder.setData(ByteString.copyFrom(byteData));
    }
    if (metadata != null) {
      builder.putAllMetadata(metadata);
    }
    DaprProtos.InvokeBindingRequest envelope = builder.build();
    return Mono.fromCallable(() -> {
      ListenableFuture<DaprProtos.InvokeBindingResponse> futureResponse = client.invokeBinding(envelope);
      return objectSerializer.deserialize(futureResponse.get().getData().toByteArray(), clazz);
    });
  } catch (Exception ex) {
    return Mono.error(ex);
  }
}
 
Example 9
Source File: ZeroCopyIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
	try {
		ZeroCopyHttpOutputMessage zeroCopyResponse = (ZeroCopyHttpOutputMessage) response;
		Resource logo = new ClassPathResource("spring.png", ZeroCopyIntegrationTests.class);
		File logoFile = logo.getFile();
		zeroCopyResponse.getHeaders().setContentType(MediaType.IMAGE_PNG);
		zeroCopyResponse.getHeaders().setContentLength(logoFile.length());
		return zeroCopyResponse.writeWith(logoFile, 0, logoFile.length());
	}
	catch (Throwable ex) {
		return Mono.error(ex);
	}
}
 
Example 10
Source File: AbstractReactiveTransactionAspectTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Void> exceptional(Throwable t) {
	if (t != null) {
		return Mono.error(t);
	}
	return Mono.empty();
}
 
Example 11
Source File: JettyRequestUpgradeStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler,
		@Nullable String subProtocol, Supplier<HandshakeInfo> handshakeInfoFactory) {

	ServerHttpRequest request = exchange.getRequest();
	ServerHttpResponse response = exchange.getResponse();

	HttpServletRequest servletRequest = getHttpServletRequest(request);
	HttpServletResponse servletResponse = getHttpServletResponse(response);

	HandshakeInfo handshakeInfo = handshakeInfoFactory.get();
	DataBufferFactory factory = response.bufferFactory();

	JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter(
			handler, session -> new JettyWebSocketSession(session, handshakeInfo, factory));

	startLazily(servletRequest);

	Assert.state(this.factory != null, "No WebSocketServerFactory available");
	boolean isUpgrade = this.factory.isUpgradeRequest(servletRequest, servletResponse);
	Assert.isTrue(isUpgrade, "Not a WebSocket handshake");

	try {
		adapterHolder.set(new WebSocketHandlerContainer(adapter, subProtocol));
		this.factory.acceptWebSocket(servletRequest, servletResponse);
	}
	catch (IOException ex) {
		return Mono.error(ex);
	}
	finally {
		adapterHolder.remove();
	}

	return Mono.empty();
}
 
Example 12
Source File: ErrorHandlerIntegrationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
	Exception error = new UnsupportedOperationException();
	String path = request.getURI().getPath();
	if (path.endsWith("response-body-error")) {
		return response.writeWith(Mono.error(error));
	}
	else if (path.endsWith("handling-error")) {
		return Mono.error(error);
	}
	else {
		return Mono.empty();
	}
}
 
Example 13
Source File: DeliveryRunnable.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Mono<Void> runStep(MailQueue.MailQueueItem queueItem) {
    TimeMetric timeMetric = metricFactory.timer(REMOTE_DELIVERY_TRIAL);
    try {
        return processMail(queueItem)
            .doOnSuccess(any -> timeMetric.stopAndPublish().logWhenExceedP99(DEFAULT_100_MS_THRESHOLD));
    } catch (Throwable e) {
        return Mono.error(e);
    }
}
 
Example 14
Source File: CompositeNotifierTest.java    From Moss with Apache License 2.0 5 votes vote down vote up
@Test
public void should_continue_on_exception() {
    Notifier notifier1 = ev -> Mono.error(new IllegalStateException("Test"));
    TestNotifier notifier2 = new TestNotifier();
    CompositeNotifier compositeNotifier = new CompositeNotifier(Arrays.asList(notifier1, notifier2));

    StepVerifier.create(compositeNotifier.notify(APP_DOWN)).verifyComplete();

    assertThat(notifier2.getEvents()).containsOnly(APP_DOWN);
}
 
Example 15
Source File: CustomExceptionHandler.java    From lion with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {

    log.error(ex.getMessage());

    /**
     * 按照异常类型进行处理
     */
    HttpStatus httpStatus;
    String body;
    if (ex instanceof BlockException) {
        httpStatus = HttpStatus.TOO_MANY_REQUESTS;
        // Too Many Request Server
        body = JsonUtil.jsonObj2Str(Result.failure(httpStatus.value(), "前方拥挤,请稍后再试"));
    } else {
        //ResponseStatusException responseStatusException = (ResponseStatusException) ex;
        //httpStatus = responseStatusException.getStatus();
        //body = responseStatusException.getMessage();

        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        // Internal Server Error
        body = JsonUtil.jsonObj2Str(Result.failure(httpStatus.value(), "调用失败,服务不可用"));
    }
    /**
     * 封装响应体,此body可修改为自己的jsonBody
     */
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);
    result.put("body", body);
    /**
     * 错误记录
     */
    ServerHttpRequest request = exchange.getRequest();
    log.error("[全局异常处理]异常请求路径:{},记录异常信息:{}", request.getPath(), body);
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    Mono<Void> mono = RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(exchange, response));
    exceptionHandlerResult.remove();
    return mono;
}
 
Example 16
Source File: CassandraMailRepositoryWithFakeImplementationsTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<MimeMessage> read(MimeMessagePartsId blobIds) {
    return Mono.error(new RuntimeException("Expected failure while reading"));
}
 
Example 17
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private Mono<Object> decodeContent(MethodParameter parameter, Message<?> message,
		boolean isContentRequired, Flux<DataBuffer> content, MimeType mimeType) {

	ResolvableType targetType = ResolvableType.forMethodParameter(parameter);
	Class<?> resolvedType = targetType.resolve();
	ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
	ResolvableType elementType = (adapter != null ? targetType.getGeneric() : targetType);
	isContentRequired = isContentRequired || (adapter != null && !adapter.supportsEmpty());
	Consumer<Object> validator = getValidator(message, parameter);

	Map<String, Object> hints = Collections.emptyMap();

	for (Decoder<?> decoder : this.decoders) {
		if (decoder.canDecode(elementType, mimeType)) {
			if (adapter != null && adapter.isMultiValue()) {
				Flux<?> flux = content
						.map(buffer -> decoder.decode(buffer, elementType, mimeType, hints))
						.onErrorResume(ex -> Flux.error(handleReadError(parameter, message, ex)));
				if (isContentRequired) {
					flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(parameter, message)));
				}
				if (validator != null) {
					flux = flux.doOnNext(validator);
				}
				return Mono.just(adapter.fromPublisher(flux));
			}
			else {
				// Single-value (with or without reactive type wrapper)
				Mono<?> mono = content.next()
						.map(buffer -> decoder.decode(buffer, elementType, mimeType, hints))
						.onErrorResume(ex -> Mono.error(handleReadError(parameter, message, ex)));
				if (isContentRequired) {
					mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(parameter, message)));
				}
				if (validator != null) {
					mono = mono.doOnNext(validator);
				}
				return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono));
			}
		}
	}

	return Mono.error(new MethodArgumentResolutionException(
			message, parameter, "Cannot decode to [" + targetType + "]" + message));
}
 
Example 18
Source File: HybridBlobStoreTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<BlobId> save(BucketName bucketName, String data, StoragePolicy storagePolicy) {
    return Mono.error(new RuntimeException("broken everywhere"));
}
 
Example 19
Source File: SpannerConnection.java    From cloud-spanner-r2dbc with Apache License 2.0 4 votes vote down vote up
@Override
public Publisher<Void> setTransactionIsolationLevel(IsolationLevel isolationLevel) {
  return Mono.error(
      new UnsupportedOperationException("Changing isolation level is not supported."));
}
 
Example 20
Source File: HybridBlobStoreTest.java    From james-project with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<BlobId> save(BucketName bucketName, byte[] data, StoragePolicy storagePolicy) {
    return Mono.error(new RuntimeException("broken everywhere"));
}