System.Threading.Tasks.Task.FromException(System.Exception)

Here are the examples of the csharp api System.Threading.Tasks.Task.FromException(System.Exception) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

524 Examples 7

19 View Source File : ControllerTestClient.cs
License : MIT License
Project Creator : Azure

public Task<MethodCallResponseApiModel> NodeMethodCallAsync(
            string endpointId, MethodCallRequestApiModel content, CancellationToken ct) {
            return Task.FromException<MethodCallResponseApiModel>(new NotImplementedException());
        }

19 View Source File : ControllerTestClient.cs
License : MIT License
Project Creator : Azure

public Task<MethodMetadataResponseApiModel> NodeMethodGetMetadataAsync(
            string endpointId, MethodMetadataRequestApiModel content, CancellationToken ct) {
            return Task.FromException<MethodMetadataResponseApiModel>(new NotImplementedException());
        }

19 View Source File : ControllerTestClient.cs
License : MIT License
Project Creator : Azure

public Task<BrowsePathResponseApiModel> NodeBrowsePathAsync(string endpointId,
            BrowsePathRequestApiModel content, CancellationToken ct) {
            return Task.FromException<BrowsePathResponseApiModel>(new NotImplementedException());
        }

19 View Source File : ControllerTestClient.cs
License : MIT License
Project Creator : Azure

public Task<string> GetServiceStatusAsync(CancellationToken ct) {
            return Task.FromException<string>(new NotImplementedException());
        }

19 View Source File : TaskStatusRequestHandlerTest.cs
License : MIT License
Project Creator : Azure

[Fact]
        public async Task BackgroundTaskExceptionTest()
        {
            Task TestTask() => Task.FromException(new SelfRefException("foo"));

            (string correlationId, BackgroundTaskStatus backgroundTaskStatus) = BackgroundTask.Run(TestTask, "test", CancellationToken.None);

            string payload = @"{
                    ""schemaVersion"": ""1.0"",
                    ""correlationId"": ""<correlationId>""
                }".Replace("<correlationId>", correlationId);
            var taskStatusRequestHandler = new TaskStatusRequestHandler();

            await Task.Delay(TimeSpan.FromSeconds(1));

            Option<string> response = await taskStatusRequestHandler.HandleRequest(Option.Some(payload), CancellationToken.None);

            replacedert.True(response.HasValue);
            TaskStatusResponse taskStatusResponse = response.OrDefault().FromJson<TaskStatusResponse>();
            replacedert.NotNull(taskStatusResponse);
            replacedert.Equal(taskStatusResponse.CorrelationId, correlationId);
            replacedert.Equal(BackgroundTaskRunStatus.Failed, taskStatusResponse.Status);
            replacedert.NotNull(taskStatusResponse.Message);
        }

19 View Source File : RuntimeInfoProviderTest.cs
License : MIT License
Project Creator : Azure

private IDockerClient SetupDockerClient(string nonExistingContainer, params string[] containers)
        {
            var dockerClient = new Mock<IDockerClient>();
            var dockerContainer = new Mock<IContainerOperations>();
            var dockerSystem = new Mock<ISystemOperations>();
            var containerList = containers.Select(c => new ContainerListResponse { ID = c }).ToList();
            var systemInfoResponse = new SystemInfoResponse() { OSType = OperatingSystemType, Architecture = Architecture, ServerVersion = "42" };

            dockerClient.Setup(call => call.Containers).Returns(dockerContainer.Object);
            dockerClient.Setup(call => call.System).Returns(dockerSystem.Object);

            dockerContainer.Setup(
                call => call.ListContainersAsync(It.IsAny<ContainersListParameters>(), It.IsAny<CancellationToken>()))
                            .Returns(() => Task.FromResult(containerList as IList<ContainerListResponse>));

            dockerContainer.Setup(
                call => call.InspectContainerAsync(It.IsAny<string>(), It.IsAny<CancellationToken>()))
                            .Returns(
                                (string a, CancellationToken b) =>
                                {
                                    if (a.Equals(nonExistingContainer))
                                    {
                                        return Task.FromException<ContainerInspectResponse>(new DockerContainerNotFoundException(0, null));
                                    }
                                    else
                                    {
                                        return Task.FromResult(new ContainerInspectResponse()
                                        {
                                            Name = "/" + a,
                                            Config = new Config() { Image = "dummy:latest" },
                                            State = new ContainerState() { Status = "running" }
                                        });
                                    }
                                });

            dockerSystem.Setup(
                call => call.GetSystemInfoAsync(It.IsAny<CancellationToken>()))
                            .Returns(() => Task.FromResult(systemInfoResponse));

            return dockerClient.Object;
        }

19 View Source File : ModuleMessageProcessorTest.cs
License : MIT License
Project Creator : Azure

internal ThrowingDeviceProxyBuilder WithThrow<T>()
            where T : Exception
        {
            this.responses.Add(() => Task.FromException(Activator.CreateInstance(typeof(T), "test error") as Exception));
            return this;
        }

19 View Source File : CloudMessageProcessorTests.cs
License : MIT License
Project Creator : Azure

internal static Func<Task> Throw<T>()
            where T : Exception, new()
        {
            return () => Task.FromException(new T());
        }

19 View Source File : UpdatableEncryptedStoreTest.cs
License : MIT License
Project Creator : Azure

public Task<string> DecryptAsync(string encryptedText)
            {
                if (!this.encryptedVals.TryGetValue(encryptedText, out string plainText))
                {
                    return Task.FromException<string>(new InvalidOperationException("Error decrypting"));
                }

                return Task.FromResult(plainText);
            }

19 View Source File : TestReportUtilTest.cs
License : MIT License
Project Creator : Azure

private Task<ITestResultReport> MockTestResultReport(bool throwException)
        {
            if (!throwException)
            {
                return Task.FromResult<ITestResultReport>(new CountingReport(
                  "mock",
                  TestMode.Connectivity,
                  "mock",
                  "mock",
                  "mock",
                  "mock",
                  23,
                  21,
                  12,
                  0,
                  0,
                  new List<TestOperationResult>(),
                  new List<TestOperationResult>(),
                  new List<TestOperationResult>(),
                  new List<TestOperationResult>(),
                  Option.None<EventHubSpecificReportComponents>(),
                  Option.None<DateTime>()));
            }

            return Task.FromException<ITestResultReport>(new ApplicationException("Inject exception for testing"));
        }

19 View Source File : ProducerTests.cs
License : MIT License
Project Creator : Azure-Samples

[Fact]
        public async Task Command_should_not_be_produced_by_unavailable_ingestion_service()
        {
            var messagesCollectorMock = new Mock<IAsyncCollector<EventData>>();
            var loggerMock = new Mock<ILogger>();

            var command = new DefaultCommand
            {
                Header = new MessageHeader(Guid.NewGuid().ToString(), nameof(DefaultCommand), nameof(Sources.Orchestrator)),
            };

            messagesCollectorMock
              .Setup(x => x.AddAsync(It.IsAny<EventData>(), default))
              .Returns(
                Task.FromException(new Exception())
              );

            Producer producer = new Producer(messagesCollectorMock.Object, loggerMock.Object);
            ProducerResult result = await producer.ProduceCommandWithRetryAsync(command);

            replacedert.NotNull(result);
            replacedert.False(result.Valid);
        }

19 View Source File : Startup.cs
License : MIT License
Project Creator : AzureAD

private Task AuthenticationFailed(AuthenticationFailedContext arg)
        {
            // For debugging purposes only!
            string authenticationExceptionMessage = $"{{AuthenticationFailed: '{arg.Exception.Message}'}}";

            arg.Response.ContentLength = authenticationExceptionMessage.Length;
            arg.Response.Body.WriteAsync(
                Encoding.UTF8.GetBytes(authenticationExceptionMessage), 
                0,
                authenticationExceptionMessage.Length);

            return Task.FromException(arg.Exception);
        }

19 View Source File : StorageQueueMessagePumpTests.cs
License : MIT License
Project Creator : BookBeat

[Test]
        public async Task Should_release_semapreplaced_if_exception()
        {
            //arrange
            var settings = new TestMessageSettings
            {
                DeadLetterDeliveryLimit = 1,
                PrefetchCount = 1,
                MaxConcurrentCalls = 1
            };
            var messageCount = 1;
            var messages = new List<StorageQueueMessage>();
            for (var i = 0; i < messageCount; i++)
            {
                messages.Add(new StorageQueueMessage(new LongRunningTestCommand { Message = i.ToString() }));
            }

            _clientMock.Setup(x => x.GetMessagesAsync<LongRunningTestCommand>(messageCount, It.IsAny<TimeSpan?>()))
                .ReturnsAsync(messages);
            var pump = new StorageQueueMessagePump(_clientMock.Object, settings, Mock.Of<ILog>());
            Func<StorageQueueMessage, CancellationToken, Task> function = (a, b) =>
            {
                return Task.FromException<Exception>(new Exception());
            };
            //act
            await pump.PumpAsync<LongRunningTestCommand>(function, CancellationToken.None);
            await Task.Delay(100);
            //replacedert
            pump._maxConcurrent.CurrentCount.Should().Be(1);
            
        }

19 View Source File : AcsSmsAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity,
            CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(
                new NotImplementedException("ACS SMS adapter does not support updateActivity."));
        }

19 View Source File : AcsSmsAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference,
            CancellationToken cancellationToken)
        {
            return Task.FromException(new NotImplementedException("ACS SMS adapter does not support deleteActivity."));
        }

19 View Source File : InfobipAdapterBase.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity,
            CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(
                new NotImplementedException("Infobip adapter does not support updateActivity."));
        }

19 View Source File : InfobipAdapterBase.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference,
            CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(
                new NotImplementedException("Infobip adapter does not support updateActivity."));
        }

19 View Source File : GoogleBusinessMessagingAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(new NotImplementedException("GBM adapter does not support updateActivity."));
        }

19 View Source File : AlexaAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(new NotImplementedException("Alexa adapter does not support updateActivity."));
        }

19 View Source File : AlexaAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
        {
            return Task.FromException(new NotImplementedException("Alexa adapter does not support deleteActivity."));
        }

19 View Source File : ZoomAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task<ResourceResponse> UpdateActivityAsync(ITurnContext turnContext, Activity activity, CancellationToken cancellationToken)
        {
            return Task.FromException<ResourceResponse>(new NotImplementedException("Zoom adapter does not support updateActivity."));
        }

19 View Source File : ZoomAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
        {
            return Task.FromException(new NotImplementedException("Zoom adapter does not support deleteActivity."));
        }

19 View Source File : GoogleBusinessMessagingAdapter.cs
License : MIT License
Project Creator : BotBuilderCommunity

public override Task DeleteActivityAsync(ITurnContext turnContext, ConversationReference reference, CancellationToken cancellationToken)
        {
            return Task.FromException(new NotImplementedException("GBM adapter does not support deleteActivity."));
        }

19 View Source File : TestRenderer.cs
License : MIT License
Project Creator : bUnit-dev

public new Task DispatchEventAsync(ulong eventHandlerId, EventFieldInfo fieldInfo, EventArgs eventArgs)
		{
			if (fieldInfo is null)
				throw new ArgumentNullException(nameof(fieldInfo));

			ResetUnhandledException();

			var result = Dispatcher.InvokeAsync(() =>
			{
				try
				{
					return base.DispatchEventAsync(eventHandlerId, fieldInfo, eventArgs);
				}
				catch (ArgumentException ex) when (string.Equals(ex.Message, $"There is no event handler replacedociated with this event. EventId: '{eventHandlerId}'. (Parameter 'eventHandlerId')", StringComparison.Ordinal))
				{
					var betterExceptionMsg = new UnknownEventHandlerIdException(eventHandlerId, fieldInfo, ex);
					return Task.FromException(betterExceptionMsg);
				}
			});

			if (result.IsFaulted && result.Exception is not null)
			{
				HandleException(result.Exception);
			}

			replacedertNoUnhandledExceptions();

			return result;
		}

19 View Source File : CrashReportCommand.cs
License : GNU General Public License v3.0
Project Creator : chaincase-app

public override Task<int> InvokeAsync(IEnumerable<string> args)
		{
			try
			{
				Options.Parse(args);

				CrashReporter.SetShowCrashReport(ExceptionString, int.Parse(Attempts));
			}
			catch (Exception ex)
			{
				Task.FromException(ex);
			}

			return Task.FromResult(0);
		}

19 View Source File : WasabiClientTests.cs
License : GNU General Public License v3.0
Project Creator : chaincase-app

[Fact]
		public async Task GetTransactionsTestAsync()
		{
			var mempool = Enumerable.Range(0, 1_100).Select(_ => CreateTransaction()).ToArray();

			Task<HttpResponseMessage> FakeServerCode(HttpMethod method, string action, NameValueCollection parameters, string body)
			{
				replacedert.True(parameters.Count <= 10);

				IEnumerable<uint256> requestedTxIds = parameters["transactionIds"].Split(",").Select(x => uint256.Parse(x));
				IEnumerable<string> result = mempool.Where(tx => requestedTxIds.Contains(tx.GetHash())).Select(tx => tx.ToHex());

				var response = new HttpResponseMessage(HttpStatusCode.OK);
				response.Content = new StringContent(JsonConvert.SerializeObject(result));
				return Task.FromResult(response);
			};

			var torHttpClient = new MockTorHttpClient();
			torHttpClient.OnSendAsync = FakeServerCode;
			var client = new WasabiClient(torHttpClient);
			replacedert.Empty(WasabiClient.TransactionCache);

			// Requests one transaction
			var searchedTxId = mempool[0].GetHash();
			var txs = await client.GetTransactionsAsync(Network.Main, new[] { searchedTxId }, CancellationToken.None);

			replacedert.Equal(searchedTxId, txs.First().GetHash());
			replacedert.NotEmpty(WasabiClient.TransactionCache);
			replacedert.True(WasabiClient.TransactionCache.ContainsKey(searchedTxId));

			// Requests 20 transaction
			var searchedTxIds = mempool[..20].Select(x => x.GetHash());
			txs = await client.GetTransactionsAsync(Network.Main, searchedTxIds, CancellationToken.None);
			replacedert.Equal(20, txs.Count());

			// Requests 1100 transaction
			searchedTxIds = mempool.Select(x => x.GetHash());
			txs = await client.GetTransactionsAsync(Network.Main, searchedTxIds, CancellationToken.None);
			replacedert.Equal(1_100, txs.Count());
			replacedert.Equal(1_000, WasabiClient.TransactionCache.Count());

			replacedert.Subset(WasabiClient.TransactionCache.Keys.ToHashSet(), txs.TakeLast(1_000).Select(x => x.GetHash()).ToHashSet());

			// Requests transactions that are already in the cache
			torHttpClient.OnSendAsync = (verb, action, parameters, body) =>
				Task.FromException<HttpResponseMessage>(
					new InvalidOperationException("The transaction should already be in the client cache. Http request was unexpected."));

			var expectedTobeCachedTxId = mempool.Last().GetHash();
			txs = await client.GetTransactionsAsync(Network.Main, new[] { expectedTobeCachedTxId }, CancellationToken.None);
			replacedert.Equal(expectedTobeCachedTxId, txs.Last().GetHash());

			// Requests fails with Bad Request
			torHttpClient.OnSendAsync = (verb, action, parameters, body) =>
			{
				var response = new HttpResponseMessage(HttpStatusCode.BadRequest);
				response.Content = new StringContent("\"Some RPC problem...\"");
				return Task.FromResult(response);
			};

			var ex = await replacedert.ThrowsAsync<HttpRequestException>(async () =>
				await client.GetTransactionsAsync(Network.Main, new[] { RandomUtils.GetUInt256() }, CancellationToken.None));
			replacedert.Equal("Bad Request\nSome RPC problem...", ex.Message);
		}

19 View Source File : PostDataStream.cs
License : MIT License
Project Creator : chromelyapps

public override Task FlushAsync(CancellationToken cancellationToken)
        {
            if (cancellationToken.IsCancellationRequested)
                return Task.FromCanceled(cancellationToken);

            try
            {
                Flush();
                return Task.CompletedTask;
            }
            catch (Exception ex)
            {
                return Task.FromException(ex);
            }
        }

19 View Source File : UtServer.cs
License : MIT License
Project Creator : CityOfZion

[TestMethod]
        [Ignore]
        public void Start_PeerConnectionThrowException_WarningMessageIsLoggedServerKeepListeningForPeers()
        {
            // Arrange             
            var connectionException = new Exception("The network error");
            var expectedLoggedWarningMessage = $"Something went wrong with {_peerEndPoint}. Exception: {connectionException}";

            var peerFactoryMock = AutoMockContainer.GetMock<IPeerFactory>();

            peerFactoryMock
                .Setup(x => x.ConnectTo(_peerEndPoint))
                .Returns(Task.FromException<IPeer>(connectionException));

            var loggerMock = AutoMockContainer.GetMock<ILogger<Server>>();
            var peerListenerMock = AutoMockContainer.GetMock<IPeerListener>();
            var server = AutoMockContainer.Create<Server>();

            // Act
            server.Start();

            // replacedert
            peerFactoryMock.Verify(x => x.ConnectTo(_peerEndPoint), Times.Once);
            loggerMock.Verify(x => x.LogWarning(It.Is<string>(msg => msg.Contains(expectedLoggedWarningMessage))), Times.Once);
            peerListenerMock.Verify(x => x.Start(), Times.Once);        
        }

19 View Source File : ChannelDemuxer.cs
License : MIT License
Project Creator : CoreWCF

public Task DispatchAsync(RequestContext context)
            {
                return Task.FromException(new NotImplementedException());
            }

19 View Source File : ChannelDemuxer.cs
License : MIT License
Project Creator : CoreWCF

public Task DispatchAsync(Message message)
            {
               return Task.FromException(new NotImplementedException());
            }

19 View Source File : SecurityServiceDispatcher.cs
License : MIT License
Project Creator : CoreWCF

public override Task DispatchAsync(Message message)
        {
            return Task.FromException(new NotImplementedException());
        }

19 View Source File : TaskMethodInvoker.cs
License : MIT License
Project Creator : CoreWCF

public ValueTask<(Task returnValue, object[] outputs)> InvokeAsyncCore(object instance, object[] inputs)
        {
            EnsureIsInitialized();

            if (instance == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxNoServiceObject));
            }

            if (inputs == null)
            {
                if (_inputParameterCount > 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInputParametersToServiceNull, _inputParameterCount)));
                }
            }
            else if (inputs.Length != _inputParameterCount)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInputParametersToServiceInvalid, _inputParameterCount, inputs.Length)));
            }

            object[] outputs = EmptyArray<object>.Allocate(_outputParameterCount);

            //AsyncMethodInvoker.StartOperationInvokePerformanceCounters(taskMethod.Name);

            object returnValue;
            //bool callFailed = true;
            //bool callFaulted = false;
            //ServiceModelActivity activity = null;
            //Activity boundActivity = null;

            try
            {
                //AsyncMethodInvoker.CreateActivityInfo(ref activity, ref boundActivity);
                //AsyncMethodInvoker.StartOperationInvokeTrace(taskMethod.Name);

                //if (DiagnosticUtility.ShouldUseActivity)
                //{
                //    string activityName = SR.Format(SR.ActivityExecuteMethod, taskMethod.DeclaringType.FullName, taskMethod.Name);
                //    ServiceModelActivity.Start(activity, activityName, ActivityType.ExecuteUserCode);
                //}

                returnValue = _invokeDelegate(instance, inputs, outputs);

                if (returnValue == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(Task));
                }

                var returnValueTask = returnValue as Task;

                if (returnValueTask != null)
                {
                    // Return ValueTask which comletes once the task has completed
                    if (returnValueTask.IsCompleted)
                    {
                        if (returnValueTask.IsFaulted)
                        {
                            return new ValueTask<(Task returnValue, object[] outputs)>(Task.FromException<(Task returnValue, object[] outputs)>(ConvertExceptionForFaultedTask(returnValueTask)));
                        }
                        else
                        {
                            return new ValueTask<(Task returnValue, object[] outputs)>((returnValueTask, outputs));
                        }
                    }
                    else
                    {
                        Task<(Task returnValue, object[] outputs)> completionTask = returnValueTask.ContinueWith(antecedant =>
                        {
                            if (returnValueTask.IsFaulted)
                            {
                                throw ConvertExceptionForFaultedTask(antecedant);
                            }
                            else
                            {
                                return (returnValue: antecedant, outputs);
                            }
                        });

                        return new ValueTask<(Task returnValue, object[] outputs)>(completionTask);
                    }
                    //await returnValueTask;
                }

                // returnValue is null
                return new ValueTask<(Task returnValue, object[] outputs)>((returnValueTask, outputs));
            }
            finally
            {
                // TODO: When brining boundActivity back, make sure it executes in the correct order with relation to
                // called task completing.
                //if (boundActivity != null)
                //{
                //    ((IDisposable)boundActivity).Dispose();
                //}

                //ServiceModelActivity.Stop(activity);

                // Any exception above means InvokeEnd will not be called, so complete it here.
                //if (callFailed || callFaulted)
                //{
                //AsyncMethodInvoker.StopOperationInvokeTrace(callFailed, callFaulted, TaskMethod.Name);
                //AsyncMethodInvoker.StopOperationInvokePerformanceCounters(callFailed, callFaulted, TaskMethod.Name);
                //}
            }
        }

19 View Source File : BufferedOutputStream.cs
License : MIT License
Project Creator : CoreWCF

public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
        {
            return Task.FromException<int>(Fx.Exception.AsError(new NotSupportedException(SR.ReadNotSupported)));
        }

19 View Source File : NewsListUiEntry.cs
License : Apache License 2.0
Project Creator : cs-util-com

private Task LogImageLoadError(Exception e) {
            Log.w("Image Load Error: " + e); return Task.FromException(e);
        }

19 View Source File : ExceptionWrapperKeyValueStore.cs
License : Apache License 2.0
Project Creator : cs-util-com

public Task RemoveAll() {
            try { return wrappedStore.RemoveAll(); } catch (Exception e) { return Task.FromException(e); }
        }

19 View Source File : XunitTestRunner.cs
License : Apache License 2.0
Project Creator : cs-util-com

public Task RunTestOnMethod() {
                try {
                    invokeResult = methodToTest.Invoke(clreplacedInstance, null);
                    // Its an async test so the run task should wait for the test to finish
                    if (invokeResult is Task t) { return t; }
                    return Task.FromResult(invokeResult);
                }
                catch (Exception e) {
                    reportedError = ExceptionDispatchInfo.Capture(e);
                    return Task.FromException(e);
                }
            }

19 View Source File : TaskExtensions.cs
License : Apache License 2.0
Project Creator : cs-util-com

public static Task LogOnError(this Task self) {
            return self.OnError(e => Task.FromException(Log.e(e)));
        }

19 View Source File : TaskEx.cs
License : MIT License
Project Creator : cuteant

public static Task FromException(Exception exception)
        {
#if NET451
            var tcs = new TaskCompletionSource<int>();
            tcs.TrySetException(exception);
            return tcs.Task;
#else
            return Task.FromException(exception);
#endif
        }

19 View Source File : TaskEx.cs
License : MIT License
Project Creator : cuteant

public static Task<T> FromException<T>(Exception exception)
        {
#if NET451
            var tcs = new TaskCompletionSource<T>();
            tcs.TrySetException(exception);
            return tcs.Task;
#else
            return Task.FromException<T>(exception);
#endif
        }

19 View Source File : LuisIntentScorable.cs
License : MIT License
Project Creator : CXuesong

protected override Task DoneAsync(IResolver item, Scope state, CancellationToken token)
        {
            try
            {
                Cache.Remove(item);
                return base.DoneAsync(item, state, token);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

19 View Source File : MethodScorable.cs
License : MIT License
Project Creator : CXuesong

protected override Task<IBinding> PrepareAsync(IResolver item, CancellationToken token)
        {
            try
            {
                IBinding binding;
                if (Binder.Instance.TryBind(this.lambda, item, out binding))
                {
                    return Task.FromResult(binding);
                }
                else
                {
                    return Tasks<IBinding>.Null;
                }
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled<IBinding>(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException<IBinding>(error);
            }
        }

19 View Source File : ScorableBase.cs
License : MIT License
Project Creator : CXuesong

public virtual Task<object> PrepareAsync(Item item, CancellationToken token)
        {
            try
            {
                return this.inner.PrepareAsync(item, token);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled<object>(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException<object>(error);
            }
        }

19 View Source File : MethodScorable.cs
License : MIT License
Project Creator : CXuesong

protected override Task<IBinding> PrepareAsync(IResolver item, CancellationToken token)
        {
            try
            {
                IBinding binding;
                if (Binder.Instance.TryBind(this.method, item, out binding))
                {
                    return Task.FromResult(binding);
                }
                else
                {
                    return Tasks<IBinding>.Null;
                }
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled<IBinding>(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException<IBinding>(error);
            }
        }

19 View Source File : Scorables.cs
License : MIT License
Project Creator : CXuesong

Task IScorable<Item, Score>.PostAsync(Item item, object state, CancellationToken token)
        {
            return Task.FromException(new NotImplementedException());
        }

19 View Source File : Binding.cs
License : MIT License
Project Creator : CXuesong

Task IBinding.InvokeAsync(CancellationToken token)
        {
            try
            {
                var arguments = MakeArguments(this.method, this.arguments, token);

                var result = this.method.Invoke(this.instance, arguments);
                // if the result is a task, wait for its completion and propagate any exceptions
                var task = result as Task;
                if (task != null)
                {
                    return task;
                }

                return Task.CompletedTask;
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

19 View Source File : ScorableBase.cs
License : MIT License
Project Creator : CXuesong

[DebuggerStepThrough]
        Task IScorable<Item, Score>.PostAsync(Item item, object opaque, CancellationToken token)
        {
            try
            {
                var state = (State)opaque;
                if (!Hreplacedcore(item, state))
                {
                    throw new InvalidOperationException();
                }

                return this.PostAsync(item, state, token);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

19 View Source File : ScorableBase.cs
License : MIT License
Project Creator : CXuesong

protected override Task DoneAsync(OuterItem item, OuterState state, CancellationToken token)
        {
            try
            {
                if (state != null)
                {
                    return state.Scorable.DoneAsync(state.Item, state.State, token);
                }
                else
                {
                    return Task.CompletedTask;
                }
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

19 View Source File : MethodScorable.cs
License : MIT License
Project Creator : CXuesong

protected override Task PostAsync(IResolver item, IBinding state, CancellationToken token)
        {
            try
            {
                return state.InvokeAsync(token);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

19 View Source File : ScorableBase.cs
License : MIT License
Project Creator : CXuesong

[DebuggerStepThrough]
        Task IScorable<Item, Score>.DoneAsync(Item item, object opaque, CancellationToken token)
        {
            try
            {
                var state = (State)opaque;
               
                return this.DoneAsync(item, state, token);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

19 View Source File : ScorableBase.cs
License : MIT License
Project Creator : CXuesong

public virtual Task PostAsync(Item item, object state, CancellationToken token)
        {
            try
            {
                return this.inner.PostAsync(item, state, token);
            }
            catch (OperationCanceledException error)
            {
                return Task.FromCanceled(error.CancellationToken);
            }
            catch (Exception error)
            {
                return Task.FromException(error);
            }
        }

See More Examples