private static void RenderException(UnhandledException ex) { var exceptionRenderer = new TableRenderer("Exception details:", new[] { new Tuple<string, int>(ex.Source, Console.WindowWidth - 6), }); TableRenderer.SplitString(ex.Message, Console.WindowWidth - 9).ToList().ForEach(l => exceptionRenderer.RenderRow(new[] { l })); TableRenderer.SplitString(ex.StackTrace, Console.WindowWidth - 9).ToList().ForEach(l => exceptionRenderer.RenderRow(new[] { l })); if (!string.IsNullOrEmpty(ex.InnerExMessage)) TableRenderer.SplitString(ex.InnerExMessage, Console.WindowWidth - 9).ToList().ForEach(l => exceptionRenderer.RenderRow(new[] { l })); }
public static void Attempt(RetryAmount retries, Func<RetryRequired> retryFunction, UnhandledException unhandledException, params IRetryExceptionHandler[] exceptionHandlers) { int retryCount = 0; RetryRequired retry = RetryRequired.DoRetry; do { try { retryCount++; retry = retryFunction(); } catch (Exception ex) { bool handled = false; if (exceptionHandlers != null) { var handler = exceptionHandlers.FirstOrDefault(h => h.ExceptionType.IsAssignableFrom(ex.GetType())); if (handler != null) { handled = true; retry = handler.Handle(ex); } } if(!handled) { switch (unhandledException) { default: case UnhandledException.Throw: throw; case UnhandledException.TreatAsFunctionFailure_DoRetry: retry = RetryRequired.DoRetry; break; case UnhandledException.TreatAsFunctionSuccess_NotRetry: retry = RetryRequired.NotRetry; break; } } } } while (retry == RetryRequired.DoRetry && (retries.IsInfinite || retryCount < retries.Count)); }
// DispatchEvent is used in a fire-and-forget context, so it's responsible for its own // error handling. public async Task DispatchEvent(string eventDescriptorJson, string eventArgsJson) { AssertInitialized(); AssertNotDisposed(); WebEventData webEventData; try { webEventData = WebEventData.Parse(eventDescriptorJson, eventArgsJson); } catch (Exception ex) { // Invalid event data is fatal. We expect a well-behaved client to send valid JSON. Log.DispatchEventFailedToParseEventData(_logger, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Bad input data.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); return; } try { await Renderer.Dispatcher.InvokeAsync(() => { return(Renderer.DispatchEventAsync( webEventData.EventHandlerId, webEventData.EventFieldInfo, webEventData.EventArgs)); }); } catch (Exception ex) { // A failure in dispatching an event means that it was an attempt to use an invalid event id. // A well-behaved client won't do this. Log.DispatchEventFailedToDispatchEvent(_logger, webEventData.EventHandlerId.ToString(), ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Failed to dispatch event.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } }
internal void HandleClientMessage(object sender, MessageEventArgs args) { var msg = default(IMessage); try { msg = Serializer.Deserialize(args.Data, MessageTypeProvider, this); } catch (JsonServicesException ex) { if (ex.MessageId == null) { // don't know how to route a message when its identity is unknown UnhandledException?.Invoke(this, new ThreadExceptionEventArgs(ex)); return; } // handle it as an error response msg = new ResponseErrorMessage { Id = ex.MessageId, Error = new Error(ex), }; } catch (Exception ex) { // message identity is unknown because it's a generic exception UnhandledException?.Invoke(this, new ThreadExceptionEventArgs(ex)); return; } // match the response with the pending request message if (msg is ResponseMessage responseMessage) { HandleResponseMessage(responseMessage, args.Data); return; } // handle request message (server-side event) HandleRequestMessage((RequestMessage)msg); }
private void OnUnhandledException(object sender, Exceptions.UnhandledExceptionEventArgs args) { InvokeAsync(async() => { Exception exceptionThrownInHandler = null; try { await UnhandledException.InvokeAsync(args).ConfigureAwait(false); } catch (Exception e) { exceptionThrownInHandler = e; } if (exceptionThrownInHandler != null || !args.WasHandled) { ExceptionToThrow = exceptionThrownInHandler ?? args.Exception; StateHasChanged(); } }); }
// InitializeAsync is used in a fire-and-forget context, so it's responsible for its own // error handling. public Task InitializeAsync(CancellationToken cancellationToken) { Log.InitializationStarted(_logger); return(Renderer.Dispatcher.InvokeAsync(async() => { if (_initialized) { throw new InvalidOperationException("The circuit host is already initialized."); } try { _initialized = true; // We're ready to accept incoming JSInterop calls from here on await OnCircuitOpenedAsync(cancellationToken); await OnConnectionUpAsync(cancellationToken); // We add the root components *after* the circuit is flagged as open. // That's because AddComponentAsync waits for quiescence, which can take // arbitrarily long. In the meantime we might need to be receiving and // processing incoming JSInterop calls or similar. var count = Descriptors.Count; for (var i = 0; i < count; i++) { var(componentType, parameters, sequence) = Descriptors[i]; await Renderer.AddComponentAsync(componentType, parameters, sequence.ToString()); } Log.InitializationSucceeded(_logger); } catch (Exception ex) { // Report errors asynchronously. InitializeAsync is designed not to throw. Log.InitializationFailed(_logger, ex); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex), ex); } })); }
private void OnRecieve(IAsyncResult state) { EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); if (!open) { return; } try { ArtNetData recieveState = (ArtNetData)(state.AsyncState); if (recieveState == null) { // Packet was invalid continue receiving ReceiveArtNet(); } recieveState.DataLength = EndReceiveFrom(state, ref remoteEndPoint); // Protect against UDP loopback where we recieve our own packets. if (LocalEndPoint != remoteEndPoint && recieveState.Valid) { LastPacket = DateTime.Now; var packet = ArtNetPacket.FromData(recieveState); if (packet == null) { ReceiveArtNet(); } NewPacket?.Invoke(this, new NewPacketEventArgs <ArtNetPacket>((IPEndPoint)remoteEndPoint, packet)); } } catch (Exception ex) { UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, false)); } ReceiveArtNet(); }
private async Task ConsumerLoop() { RaiseEventOnThreadPool(AnalysisStarted); while (!_ppc.IsDisposed) { try { var item = await ConsumeAsync(); _current.Value = this; await item.Handler(_ppc.CancellationToken); _current.Value = null; } catch (OperationCanceledException) when(_ppc.IsDisposed) { return; } catch (Exception ex) when(!ex.IsCriticalException()) { UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, false)); Dispose(); } } }
// ReceiveByteArray is used in a fire-and-forget context, so it's responsible for its own // error handling. internal async Task ReceiveByteArray(int id, byte[] data) { AssertInitialized(); AssertNotDisposed(); try { await Renderer.Dispatcher.InvokeAsync(() => { Log.ReceiveByteArraySuccess(_logger, id); DotNetDispatcher.ReceiveByteArray(JSRuntime, id, data); }); } catch (Exception ex) { // An error completing JS interop means that the user sent invalid data, a well-behaved // client won't do this. Log.ReceiveByteArrayException(_logger, id, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid byte array.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } }
public async Task BeginInvokeDotNetFromJS(string callId, string assemblyName, string methodIdentifier, long dotNetObjectId, string argsJson) { try { AssertInitialized(); if (assemblyName == "Microsoft.AspNetCore.Components.Web" && methodIdentifier == "DispatchEvent") { Log.DispatchEventTroughJSInterop(_logger); return; } await Renderer.Dispatcher.InvokeAsync(() => { SetCurrentCircuitHost(this); Log.BeginInvokeDotNet(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId); DotNetDispatcher.BeginInvoke(callId, assemblyName, methodIdentifier, dotNetObjectId, argsJson); }); } catch (Exception ex) { UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } }
// ReceiveJSDataChunk is used in a fire-and-forget context, so it's responsible for its own // error handling. internal async Task <bool> ReceiveJSDataChunk(long streamId, long chunkId, byte[] chunk, string error) { AssertInitialized(); AssertNotDisposed(); try { return(await Renderer.Dispatcher.InvokeAsync(() => { return RemoteJSDataStream.ReceiveData(JSRuntime, streamId, chunkId, chunk, error); })); } catch (Exception ex) { // An error completing JS interop means that the user sent invalid data, a well-behaved // client won't do this. Log.ReceiveJSDataChunkException(_logger, streamId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid chunk supplied to stream.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); return(false); } }
public void Deploy(DeployContext context, byte[] filesHash) { if (!_accessIsGranted) { throw new AuthenticationException("Session should be terminated because access wasn't granted"); } if (_filesBuffer == null || _filesBuffer.Length == 0) { throw new InvalidOperationException("Files was not transfered before deployment"); } if (!FileHashIsEqual(filesHash, MD5.Create().ComputeHash(_filesBuffer))) { throw new ArgumentException("File sending was failed because it's hash is wrong"); } var callback = _dsFactory.CreateCallbackObj(); try { _accessIsGranted = false; var conf = _dsFactory.CreateConfObj(_sessionKey, context, _cFactory); if (!GetDirectoryName(conf.SurveyPath.Survey).Equals(_updatedForlder, StringComparison.InvariantCultureIgnoreCase)) { throw new ArgumentException("Current session allows deploy only to '" + _updatedForlder + "' folder"); } _logger.Info(string.Format("Starting deploy process for folder '{0}'", _updatedForlder)); RunDeployment(conf, callback, context, _filesBuffer); _logger.Info("Deploy completed successfully"); } catch (Exception ex) { callback.OnFault(UnhandledException.CreateFromEx(ex)); throw; } finally { callback.OnClose(); Dispose(); } }
public async Task DispatchEvent(string eventDescriptorJson, string eventArgs) { RendererRegistryEventDispatcher.BrowserEventDescriptor eventDescriptor = null; try { AssertInitialized(); eventDescriptor = ParseEventDescriptor(eventDescriptorJson); if (eventDescriptor == null) { return; } await Renderer.Dispatcher.InvokeAsync(() => { SetCurrentCircuitHost(this); return(RendererRegistryEventDispatcher.DispatchEvent(eventDescriptor, eventArgs)); }); } catch (Exception ex) { Log.DispatchEventFailedToDispatchEvent(_logger, eventDescriptor != null ? eventDescriptor.EventHandlerId.ToString() : null, ex); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } }
private async void CheckForUpdateAsync(object state) { if (!(state is CheckForUpdateParams)) { throw new ArgumentException($"{nameof(state)} must be of type {nameof(CheckForUpdateParams)} (current is {state.GetType().Name})"); } var args = (CheckForUpdateParams)state; try { var release = await GetReleaseAsync(); if (args.CurrentVersion != release.Version) { args.Callback?.Invoke(release); UpdateUrl = release.HtmlUrl; UpdateAvailable = true; Update = release; } else { UpdateUrl = null; UpdateAvailable = false; Update = null; } LastChecked = DateTime.Now; } catch (Exception e) { // If the handler is defined, invoke it, otherwise silently swallow these exceptions UnhandledException?.Invoke(this, e); } }
internal static void ThrowUnhandledException(Exception exc) { string[] errorsToSkip = { "Could not initialize audio output.", "Failed to create input layout for shader", "Failed to create texture" }; foreach (var item in errorsToSkip) { if (exc.Message.StartsWith(item)) { return; } } var args = new UnhandledExceptionEventArgs(exc); UnhandledException?.Invoke(null, args); if (!args.Handled) { throw exc; } }
// BeginInvokeDotNetFromJS is used in a fire-and-forget context, so it's responsible for its own // error handling. public async Task BeginInvokeDotNetFromJS(string callId, string assemblyName, string methodIdentifier, long dotNetObjectId, string argsJson) { AssertInitialized(); AssertNotDisposed(); try { await Renderer.Dispatcher.InvokeAsync(() => { Log.BeginInvokeDotNet(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId); var invocationInfo = new DotNetInvocationInfo(assemblyName, methodIdentifier, dotNetObjectId, callId); DotNetDispatcher.BeginInvokeDotNet(JSRuntime, invocationInfo, argsJson); }); } catch (Exception ex) { // We don't expect any of this code to actually throw, because DotNetDispatcher.BeginInvoke doesn't throw // however, we still want this to get logged if we do. Log.BeginInvokeDotNetFailed(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId, ex); await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Interop call failed.")); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false)); } }
private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { UnhandledException?.Invoke(sender, e.Exception); }
private void OnUnhandledException(UnhandledExceptionEventArgs e) { UnhandledException?.Invoke(this, e); }
internal void RaiseRecoverableUnhandledException(Exception e) => UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(e, false));
// An unhandled exception from the renderer is always fatal because it came from user code. // We want to notify the client if it's still connected, and then tear-down the circuit. private async void SynchronizationContext_UnhandledException(object sender, UnhandledExceptionEventArgs e) { await ReportUnhandledException((Exception)e.ExceptionObject); UnhandledException?.Invoke(this, e); }
// We want to notify the client if it's still connected, and then tear-down the circuit. private async void ReportAndInvoke_UnhandledException(object sender, Exception e) { await ReportUnhandledException(e); UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(e, isTerminating: false)); }
public static void Attempt(int retries, Func<RetryRequired> retryFunction, UnhandledException unhandledException, params IRetryExceptionHandler[] exceptionHandlers) { Attempt(new RetryAmount(retries), retryFunction, unhandledException, exceptionHandlers); }
/// <summary> /// Create an assert object. /// </summary> public Assert() { UnhandledException.Initialize(); }
private void SynchronizationContext_UnhandledException(object sender, UnhandledExceptionEventArgs e) { UnhandledException?.Invoke(this, e); }
private void RaiseUnhandledException(Exception e) { UnhandledException?.Invoke(e); }
private void Renderer_UnhandledException(object sender, Exception e) { UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(e, isTerminating: false)); }
/// <summary> /// Starts the time simulation thread /// </summary> /// <param name="name">the name of the thread to start. This is useful when debugging.</param> /// <returns>A promise that represents the end of the time simulation</returns> public Promise Start(string name = "TimeThread") { runDeferred = Deferred.Create(); runDeferred.Promise.Finally((p) => { runDeferred = null; }); Thread t = new Thread(() => { SynchronizationContext.SetSynchronizationContext(syncContext); IsRunning = true; try { current = this; while (true) { List <WorkItem> syncActions = new List <WorkItem>(); lock (syncQueue) { while (syncQueue.Count > 0) { var workItem = syncQueue[0]; syncQueue.RemoveAt(0); syncActions.Add(workItem); } } foreach (var syncAction in syncActions) { try { syncAction.Work(); } catch (Exception ex) { if (syncAction.Deferred.HasExceptionListeners) { syncAction.Deferred.Reject(ex); } else { throw; } } if (syncAction.Deferred.IsFulfilled == false) { syncAction.Deferred.Resolve(); } } Tick(); AfterTick.Fire(); } } catch (StopTimeException) { IsRunning = false; runDeferred.Resolve(); } catch (Exception ex) { IsRunning = false; var args = new TimeExceptionArgs() { Exception = ex }; BeforeUnhandledException.Fire(args); if (args.Handled) { runDeferred.Resolve(); } else { UnhandledException.Fire(ex); runDeferred.Reject(ex); } } }) { Name = name }; t.Priority = ThreadPriority.AboveNormal; t.IsBackground = true; t.Start(); return(runDeferred.Promise); }
private void ConnectiOnError(object sender, Exception exception) { UnhandledException?.Invoke(sender, exception); }
public void OnFault(UnhandledException exception) { _writer.NotifyFault(exception); }
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { UnhandledException.WriteEvent(sender, e, true); }
/// <summary> /// Creates a new WebDriver object. /// </summary> public WebDriver() { UnhandledException.Initialize(); RegisterRunningObject(); COMDisposable.Subscribe(this, typeof(ComInterfaces._WebDriver)); }
private async ValueTask InvokeAllAsync(OutgoingRequestFrame outgoingRequest, int requestId) { // The object adapter DirectCount was incremented by the caller and we are responsible to decrement it // upon completion. Ice.Instrumentation.IDispatchObserver?dispatchObserver = null; try { if (_traceLevels.Protocol >= 1) { // TODO we need a better API for tracing List <System.ArraySegment <byte> > requestData = Ice1Definitions.GetRequestData(outgoingRequest, requestId); TraceUtil.TraceSend(_adapter.Communicator, VectoredBufferExtensions.ToArray(requestData), _logger, _traceLevels); } var incomingRequest = new IncomingRequestFrame(_adapter.Communicator, outgoingRequest); var current = new Current(_adapter, incomingRequest, requestId); // Then notify and set dispatch observer, if any. Ice.Instrumentation.ICommunicatorObserver?communicatorObserver = _adapter.Communicator.Observer; if (communicatorObserver != null) { dispatchObserver = communicatorObserver.GetDispatchObserver(current, incomingRequest.Size); dispatchObserver?.Attach(); } bool amd = true; try { IObject?servant = current.Adapter.Find(current.Identity, current.Facet); if (servant == null) { amd = false; throw new ObjectNotExistException(current.Identity, current.Facet, current.Operation); } ValueTask <OutgoingResponseFrame> vt = servant.DispatchAsync(incomingRequest, current); amd = !vt.IsCompleted; if (requestId != 0) { OutgoingResponseFrame response = await vt.ConfigureAwait(false); dispatchObserver?.Reply(response.Size); SendResponse(requestId, response, amd); } } catch (System.Exception ex) { if (requestId != 0) { RemoteException actualEx; if (ex is RemoteException remoteEx && !remoteEx.ConvertToUnhandled) { actualEx = remoteEx; } else { actualEx = new UnhandledException(current.Identity, current.Facet, current.Operation, ex); } Incoming.ReportException(actualEx, dispatchObserver, current); var response = new OutgoingResponseFrame(current, actualEx); dispatchObserver?.Reply(response.Size); SendResponse(requestId, response, amd); } } }
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) => UnhandledException?.Invoke(this, e);
public virtual void OnException(object sender, Exception ex) { Console.WriteLine(ex); UnhandledException?.Invoke(sender, ex); }
public void NotifyFault(UnhandledException exception) { Console.WriteLine(); Console.WriteLine("During the deploy was obtained and unhandled exception. For more information, check the log."); RenderException(exception); }