public void ClaimOwnershipLogsErrors() { var partitionOwnership = new List <EventProcessorPartitionOwnership> { new EventProcessorPartitionOwnership { FullyQualifiedNamespace = FullyQualifiedNamespace, EventHubName = EventHubName, ConsumerGroup = ConsumerGroup, OwnerIdentifier = OwnershipIdentifier, PartitionId = PartitionId, LastModifiedTime = DateTime.UtcNow } }; var expectedException = new DllNotFoundException("BOOM!"); var mockLog = new Mock <BlobEventStoreEventSource>(); var mockContainerClient = new MockBlobContainerClient().AddBlobClient($"{FullyQualifiedNamespace}/{EventHubName}/{ConsumerGroup}/ownership/1", client => client.UploadBlobException = expectedException); var target = new BlobsCheckpointStore(mockContainerClient, DefaultRetryPolicy); target.Logger = mockLog.Object; Assert.That(async() => await target.ClaimOwnershipAsync(partitionOwnership, CancellationToken.None), Throws.Exception.EqualTo(expectedException)); mockLog.Verify(m => m.ClaimOwnershipError(PartitionId, FullyQualifiedNamespace, EventHubName, ConsumerGroup, OwnershipIdentifier, expectedException.Message)); }
public void UpdateCheckpointLogsErrorsWhenTheBlobDoesNotExist() { var checkpoint = new EventProcessorCheckpoint { FullyQualifiedNamespace = FullyQualifiedNamespace, EventHubName = EventHubName, ConsumerGroup = ConsumerGroup, PartitionId = PartitionId, }; var expectedException = new DllNotFoundException("BOOM!"); var mockLog = new Mock <BlobEventStoreEventSource>(); var mockContainerClient = new MockBlobContainerClient().AddBlobClient($"{FullyQualifiedNamespace}/{EventHubName}/{ConsumerGroup}/checkpoint/1", client => { client.UploadBlobException = expectedException; }); var target = new BlobsCheckpointStore(mockContainerClient, DefaultRetryPolicy); target.Logger = mockLog.Object; Assert.That(async() => await target.UpdateCheckpointAsync(checkpoint, new EventData(Array.Empty <byte>()), CancellationToken.None), Throws.Exception.EqualTo(expectedException)); mockLog.Verify(log => log.UpdateCheckpointError(checkpoint.PartitionId, checkpoint.FullyQualifiedNamespace, checkpoint.EventHubName, checkpoint.ConsumerGroup, expectedException.Message)); }
private IEnumerator InitializeSteam() { base.SetLastError(0, "Initializing the steam API..."); try { if (Steamworks.SteamAPI.Init()) { this.isSteamCommunicationEstablished = true; yield break; } Diagnostics.LogError("Failed to initialize the Steam API; aborting..."); Application.Quit(); yield break; } catch (DllNotFoundException ex) { DllNotFoundException exception = ex; base.SetLastError(-1, "Exception caught! check with the console log for details."); throw exception; } catch { base.SetLastError(-1); throw; } yield break; }
public void Constructor_ShouldSetInnerException() { var innerException = new DllNotFoundException(); var exception = new RfcLibraryNotFoundException(innerException); exception.InnerException.Should().Be(innerException); }
public void Ctor_Default() { var exception = new DllNotFoundException(); Assert.NotEmpty(exception.Message); Assert.Null(exception.InnerException); Assert.Equal(COR_E_DLLNOTFOUND, exception.HResult); }
public void Ctor_String() { string message = "library not found"; var exception = new DllNotFoundException(message); Assert.Equal(message, exception.Message); Assert.Null(exception.InnerException); Assert.Equal(COR_E_DLLNOTFOUND, exception.HResult); }
public void HandleExceptionRethrowsExceptionsWrappedInAggregate() { var exception = new DllNotFoundException(); var tested = new RethrowExceptionPolicy(); // act & assert var ex = Assert.Throws <ExceptionRethrownWrapper>(() => tested.HandleException(exception)); Assert.IsType(exception.GetType(), ex.InnerException); }
public void Constructor_ShouldSetInnerException() { // Arrange var innerException = new DllNotFoundException(); // Act var exception = new SapLibraryNotFoundException(innerException); // Assert exception.InnerException.Should().Be(innerException); }
public void ContainsTheRequiredKeys() { var configuration = new Configuration("123456"); var exception = new DllNotFoundException(); var severity = HandledState.ForUnhandledException(); var breadcrumbs = new Breadcrumb[0]; var session = new Session(); var @event = new Report(configuration, exception, severity, breadcrumbs, session); Assert.Equal(configuration.ApiKey, @event["apiKey"]); Assert.NotNull(@event["notifier"]); Assert.NotNull(@event["events"]); }
private void LoadUnmanagedLibraries() { string assemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); IntPtr pDll = NativeMethods.LoadLibrary(Path.Combine(assemblyPath, "SciLexer.dll")); if (pDll == IntPtr.Zero) { Exception ex = new DllNotFoundException("Could not find SciLexer.dll - This is unmanaged assembly is required by ScintillaNet.dll"); Raygun.LogException(ex); throw ex; } }
public void HandleExceptionRethrowsExceptionsWrappedInAggregate() { var exception = new DllNotFoundException(); var policySubstitute = Substitute.For <IExceptionHandlingPolicy>(); policySubstitute.When((policy) => { policy.HandleException(Arg.Any <Exception>()); }).Do((policy) => throw new VerificationException()); var policies = new List <IExceptionHandlingPolicy> { policySubstitute, default(IExceptionHandlingPolicy) }; var tested = new AggregatedExceptionHandlingPolicy(policies); // act & assert Assert.Throws <AggregateException>(() => tested.HandleException(exception)); }
public void SummaryOrdersErrorsFromMostOccuringDescending() { var error1 = new DllNotFoundException(); var error2 = new ArgumentException(); var error3 = new ArgumentException(); var error4 = new ArgumentException(); var exceptionsAggregated = new List <Exception> { error1, error2, error3, error4 }; var received = exceptionsAggregated.Summary(); var multilineRegex = new Regex($"{OpeningSequenceMultipleRegex}.?.?.?({error2.GetType().FullName}|{error2.GetType().Name}){RegexForThreeTimes}", RegexOptions.IgnoreCase | RegexOptions.Singleline); Assert.True(multilineRegex.IsMatch(received)); }
private static void Main(string[] args) { XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config")); Task.Factory.StartNew(() => { var logger = log4net.LogManager.GetLogger(typeof(Program)); log4net.ThreadContext.Properties["UserAgent"] = "some cool user agent goes here"; log4net.ThreadContext.Properties["UserId"] = System.Guid.NewGuid().ToString(); log4net.ThreadContext.Properties["SessionId"] = System.Guid.NewGuid().ToString(); var exc = new DllNotFoundException("this is some random exception!"); for (int x = 6000; x <= 7000; x++) { Console.WriteLine("Logging"); logger.Info("Info with exception" + x, exc); logger.Debug("Debug with exception" + x, exc); logger.Error("Error with exception" + x, exc); logger.Fatal("Fatal with exception" + x, exc); logger.Warn("Warn with exception" + x, exc); logger.Info("Info" + x); logger.Debug("Debug" + x); logger.Error("Error" + x); logger.Fatal("Fatal" + x); logger.Warn("Warn" + x); try { throw exc; } catch (Exception e) { logger.Error("there was an error!" + x, e); } Console.WriteLine("Logged"); Task.Delay(1000 * 2).Wait(); } }); Console.WriteLine("Sleeping"); while (true) { Task.Delay(1000).Wait(); } }
static void Main(string[] args) { InventoryDAL dal = new InventoryDAL(); var list = dal.GetAllInventory(); Console.WriteLine(" ********** All Cars **********1"); Console.WriteLine("CarId\tMake\tColor\tPet Name"); foreach (var itm in list) { Console.WriteLine($"{itm.CarId}\t{itm.Make}\t{itm.Color}" + $"\t{itm.PetName}"); } Console.WriteLine(); var car = dal.GetCar(list.OrderBy(x => x.color).Select(x => x.CarId) .First()); Console.WriteLine(" ********** First Car By Color **********"); Console.WriteLine("CarId\tMake\tColor\tPet Name"); Console.WriteLine($"{car.CarId}\t{car.Make}\t{car.Color}\t" + $"{car.PetName}"); try { dal.DeleteCar(5); Console.WriteLine("Car deleted."); } catch (Exception ex) { Console.WriteLine($"An exception occurred: {ex.Message}"); } dal.InsertAuto(new Car { Color = "Blue", Make = "Pilot", PetName = "TowMonster" }); list = dal.GetAllInventory(); var newCar = list.First(x => x.PetName == "TowMonster"); Console.WriteLine(" ********** New Car ********** "); Console.WriteLine("CarId\tMake\tColor\tPet Name"); Console.WriteLine($"{newCar.CarId}\t{newCar.Make}\t{newCar.Color}\t" + $"{newCar.PetName}"); dal.DeleteCar(newCar.Id); var petName = DllNotFoundException.LookUpPetName(car.CarId); Console.WriteLine(" ********** New Car ********** "); Console.WriteLine($"Car pet name; {petName}"); Console.Write("Press enter to continue..."); Console.ReadLine(); }
public void ListCheckpointsLogsErrors() { var expectedException = new DllNotFoundException("BOOM!"); var mockLog = new Mock <BlobEventStoreEventSource>(); var mockContainerClient = new MockBlobContainerClient() { GetBlobsAsyncException = expectedException }; var target = new BlobsCheckpointStore(mockContainerClient, DefaultRetryPolicy); target.Logger = mockLog.Object; Assert.That(async() => await target.ListCheckpointsAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup, CancellationToken.None), Throws.Exception.EqualTo(expectedException)); mockLog.Verify(m => m.ListCheckpointsError(FullyQualifiedNamespace, EventHubName, ConsumerGroup, expectedException.Message)); }
public void LargePaylaodsDropBreadcrumbsAndMetadata() { var configuration = new Configuration("123456"); var exception = new DllNotFoundException(); var severity = HandledState.ForUnhandledException(); var breadcrumbs = new Breadcrumb[] { new Breadcrumb("wow bread!", BreadcrumbType.Manual) }; var session = new Session(); var report = new Report(configuration, exception, severity, breadcrumbs, session); report.Event.Metadata.Add("small metadat", "so small"); report.Event.Metadata.Add("large metadata", new String('a', (1024 * 1024))); var data = report.Serialize(); Assert.NotNull(data); Assert.Null(report.Event.Breadcrumbs); Assert.Single(report.Event.Metadata); }
public void HandleExceptionActivatesAllNotNullPoliciesHandleException() { var exception = new DllNotFoundException(); var policySubstitute = Substitute.For <IExceptionHandlingPolicy>(); var policies = new List <IExceptionHandlingPolicy> { policySubstitute, default(IExceptionHandlingPolicy) }; var tested = new AggregatedExceptionHandlingPolicy(policies); Assert.NotNull(tested.Policies); Assert.Equal(1, tested.Policies.Count); // act tested.HandleException(exception); // assert policySubstitute.Received(1).HandleException(exception); }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Create a instance of DllNotFoundException"); try { DllNotFoundException dbz = new DllNotFoundException(); if (dbz == null) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(not null) !=ActualValue(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1:Create a instance of DllNotFoundException"); try { DllNotFoundException dbz = new DllNotFoundException(); if (dbz == null) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(not null) !=ActualValue(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return(retVal); }
private static bool TestRustNative() { bool flag; try { if (SelfCheck.RustNative_VersionCheck(5)) { return(true); } else { flag = SelfCheck.Failed("RustNative is wrong version!"); } } catch (DllNotFoundException dllNotFoundException1) { DllNotFoundException dllNotFoundException = dllNotFoundException1; flag = SelfCheck.Failed(string.Concat("RustNative library couldn't load! ", dllNotFoundException.Message)); } return(flag); }
public bool PosTest4() { bool retVal = true; String errMessage = TestLibrary.Generator.GetString(-55, false, 256, 512); TestLibrary.TestFramework.BeginScenario("PosTest4:Determine the method with Long String"); try { DllNotFoundException dnfe = new DllNotFoundException(errMessage, new Exception()); if (dnfe == null) { TestLibrary.TestFramework.LogError("009", "ExpectedValue(not null) !=ActualValue(null)"); retVal = false; } else { retVal = false; throw dnfe; } } catch (DllNotFoundException dE) { retVal = true; if (!dE.Message.Equals(errMessage)) { TestLibrary.TestFramework.LogError("010", "ExpectedValue(Message Not Be Changed) !=ActualValue(Message Be Changed)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("011", "Unexpected exception:" + e); retVal = false; } return retVal; }
public void SummarySummarizesMultipleErrors() { var error1 = new DllNotFoundException(); var error2 = new ArgumentException(); var error3 = new ArgumentException(); var error4 = new ArgumentException(); var error5 = new COMException(); var exceptionsAggregated = new List <Exception> { error1, error2, error3, error4, error5 }; var received = exceptionsAggregated.Summary(); Assert.True(received.Contains(nameof(DllNotFoundException))); Assert.True(received.Contains(nameof(ArgumentException))); Assert.True(received.Contains(nameof(COMException))); Assert.True(Regex.IsMatch(received, OpeningSequenceMultipleRegex)); Assert.True(Regex.IsMatch(received, $"{nameof(ArgumentException)}{RegexForThreeTimes}")); Assert.True(Regex.IsMatch(received, $"{nameof(DllNotFoundException)}{RegexForOnce}")); Assert.True(Regex.IsMatch(received, $"{nameof(COMException)}{RegexForOnce}")); }
public bool PosTest2() { bool retVal = true; String errMessage = TestLibrary.Generator.GetString(-55, false, 1, 255); TestLibrary.TestFramework.BeginScenario("PosTest2:Determine the error message is changed or not when the exception is thown out"); try { DllNotFoundException dnfe = new DllNotFoundException(errMessage, new Exception()); if (dnfe == null) { TestLibrary.TestFramework.LogError("003", "ExpectedValue(not null) !=ActualValue(null)"); retVal = false; } else { retVal = false; throw dnfe; } } catch (DllNotFoundException dE) { retVal = true; if (!dE.Message.Equals(errMessage)) { TestLibrary.TestFramework.LogError("004", "ExpectedValue(Message Not Be Changed) !=ActualValue(Message Be Changed)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("005", "Unexpected exception:" + e); retVal = false; } return retVal; }
public bool PosTest3() { bool retVal = true; String errMessage = String.Empty; TestLibrary.TestFramework.BeginScenario("PosTest3:Determine the method with Empty String"); try { DllNotFoundException dnfe = new DllNotFoundException(errMessage, new Exception()); if (dnfe == null) { TestLibrary.TestFramework.LogError("006", "ExpectedValue(not null) !=ActualValue(null)"); retVal = false; } else { retVal = false; throw dnfe; } } catch (DllNotFoundException dE) { retVal = true; if (!dE.Message.Equals(errMessage)) { TestLibrary.TestFramework.LogError("007", "ExpectedValue(Message Not Be Changed) !=ActualValue(Message Be Changed)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e); retVal = false; } return retVal; }
public bool PosTest1() { bool retVal = true; String errMessage = TestLibrary.Generator.GetString(-55, false, 1, 255); TestLibrary.TestFramework.BeginScenario("PosTest1:Create a instance of DllNotFoundException"); try { DllNotFoundException dnfe = new DllNotFoundException(errMessage); if (dnfe == null) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(not null) !=ActualValue(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return(retVal); }
public bool PosTest1() { bool retVal = true; String errMessage = TestLibrary.Generator.GetString(-55, false, 1, 255); TestLibrary.TestFramework.BeginScenario("PosTest1:Create a instance of DllNotFoundException"); try { DllNotFoundException dnfe = new DllNotFoundException(errMessage, new Exception()); if (dnfe == null) { TestLibrary.TestFramework.LogError("001", "ExpectedValue(not null) !=ActualValue(null)"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e); retVal = false; } return retVal; }
//取函数地址 //返回值 //0:取通用函数地址正确 public int Load(string dllPath) { var notFound = new DllNotFoundException("Dd driver dll not found."); _mHinst = LoadLibrary(dllPath); if (_mHinst.Equals(IntPtr.Zero)) { throw notFound; } var loadFailed = new DllNotFoundException("Could not load dd driver dll."); var ptr = GetProcAddress(_mHinst, "DD_btn"); if (ptr.Equals(IntPtr.Zero)) { throw loadFailed; } Btn = Marshal.GetDelegateForFunctionPointer(ptr, typeof(PDdBtn)) as PDdBtn; ptr = GetProcAddress(_mHinst, "DD_whl"); if (ptr.Equals(IntPtr.Zero)) { throw loadFailed; } Whl = Marshal.GetDelegateForFunctionPointer(ptr, typeof(PDdWhl)) as PDdWhl; ptr = GetProcAddress(_mHinst, "DD_mov"); if (ptr.Equals(IntPtr.Zero)) { throw loadFailed; } Mov = Marshal.GetDelegateForFunctionPointer(ptr, typeof(PDdMov)) as PDdMov; ptr = GetProcAddress(_mHinst, "DD_key"); if (ptr.Equals(IntPtr.Zero)) { throw loadFailed; } Key = Marshal.GetDelegateForFunctionPointer(ptr, typeof(PDdKey)) as PDdKey; ptr = GetProcAddress(_mHinst, "DD_movR"); if (ptr.Equals(IntPtr.Zero)) { throw loadFailed; } MovR = Marshal.GetDelegateForFunctionPointer(ptr, typeof(PDdMovR)) as PDdMovR; ptr = GetProcAddress(_mHinst, "DD_str"); if (ptr.Equals(IntPtr.Zero)) { throw loadFailed; } Str = Marshal.GetDelegateForFunctionPointer(ptr, typeof(PDdStr)) as PDdStr; ptr = GetProcAddress(_mHinst, "DD_todc"); if (ptr.Equals(IntPtr.Zero)) { throw loadFailed; } Todc = Marshal.GetDelegateForFunctionPointer(ptr, typeof(PDdTodc)) as PDdTodc; return(0); }
private static WrapperEngineLoadException WrapDllNotFoundException( DllNotFoundException originalDllNotFoundException) { string originalMessage = originalDllNotFoundException.Message; string description; string message; bool isMonoRuntime = Utils.IsMonoRuntime(); if ((isMonoRuntime && originalMessage == DllName.Universal) || originalMessage.ContainsQuotedValue(DllName.Universal)) { const string buildInstructionsUrl = "https://github.com/pauldotknopf/vroomjs-core#maclinux"; bool quoteDescription = false; var stringBuilderPool = StringBuilderPool.Shared; StringBuilder descriptionBuilder = stringBuilderPool.Rent(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Architecture osArchitecture = RuntimeInformation.OSArchitecture; if (osArchitecture == Architecture.X64 || osArchitecture == Architecture.X86) { descriptionBuilder.Append(originalMessage); quoteDescription = true; } else { descriptionBuilder.AppendFormat(CoreStrings.Engine_ProcessorArchitectureNotSupported, osArchitecture.ToString().ToLowerInvariant()); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { descriptionBuilder.AppendFormat(CoreStrings.Engine_AssemblyNotFound, DllName.ForUnix); descriptionBuilder.Append(" "); descriptionBuilder.AppendFormat(Strings.Engine_BuildNativeAssemblies, DllName.ForUnix, "libv8.so." + EngineVersion, buildInstructionsUrl); } else { descriptionBuilder.Append(CoreStrings.Engine_OperatingSystemNotSupported); } description = descriptionBuilder.ToString(); stringBuilderPool.Return(descriptionBuilder); message = JsErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName, quoteDescription); } else { description = originalMessage; message = JsErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName, true); } var wrapperEngineLoadException = new WrapperEngineLoadException(message, EngineName, EngineVersion, originalDllNotFoundException) { Description = description }; return(wrapperEngineLoadException); }
private static WrapperEngineLoadException WrapDllNotFoundException( DllNotFoundException originalDllNotFoundException) { string originalMessage = originalDllNotFoundException.Message; string description; string message; bool isMonoRuntime = Utils.IsMonoRuntime(); if ((isMonoRuntime && originalMessage == DllName.Universal) || originalMessage.ContainsQuotedValue(DllName.Universal)) { const string buildInstructionsUrl = "https://github.com/Microsoft/ChakraCore/wiki/Building-ChakraCore#{0}"; const string manualInstallationInstructionsUrl = "https://github.com/Taritsyn/JavaScriptEngineSwitcher/wiki/ChakraCore#{0}"; Architecture osArchitecture = RuntimeInformation.OSArchitecture; var stringBuilderPool = StringBuilderPool.Shared; StringBuilder descriptionBuilder = stringBuilderPool.Rent(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { descriptionBuilder.AppendFormat(CoreStrings.Engine_AssemblyNotFound, DllName.ForWindows); descriptionBuilder.Append(" "); if (osArchitecture == Architecture.X64 || osArchitecture == Architecture.X86) { descriptionBuilder.AppendFormat(CoreStrings.Engine_NuGetPackageInstallationRequired, Utils.Is64BitProcess() ? "JavaScriptEngineSwitcher.ChakraCore.Native.win-x64" : "JavaScriptEngineSwitcher.ChakraCore.Native.win-x86" ); } else if (osArchitecture == Architecture.Arm) { descriptionBuilder.AppendFormat(CoreStrings.Engine_NuGetPackageInstallationRequired, "JavaScriptEngineSwitcher.ChakraCore.Native.win-arm"); } else { descriptionBuilder.AppendFormat(CoreStrings.Engine_NoNuGetPackageForProcessorArchitecture, "JavaScriptEngineSwitcher.ChakraCore.Native.win*", osArchitecture.ToString().ToLowerInvariant() ); descriptionBuilder.Append(" "); descriptionBuilder.AppendFormat(Strings.Engine_BuildNativeAssemblyForCurrentProcessorArchitecture, DllName.ForWindows, string.Format(buildInstructionsUrl, "windows") ); } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { descriptionBuilder.AppendFormat(CoreStrings.Engine_AssemblyNotFound, DllName.ForLinux); descriptionBuilder.Append(" "); if (isMonoRuntime) { descriptionBuilder.AppendFormat(Strings.Engine_ManualInstallationUnderMonoRequired, "JavaScriptEngineSwitcher.ChakraCore.Native.linux-*", string.Format(manualInstallationInstructionsUrl, "linux") ); } else { if (osArchitecture == Architecture.X64) { descriptionBuilder.AppendFormat(CoreStrings.Engine_NuGetPackageInstallationRequired, "JavaScriptEngineSwitcher.ChakraCore.Native.linux-x64"); } else { descriptionBuilder.AppendFormat(CoreStrings.Engine_NoNuGetPackageForProcessorArchitecture, "JavaScriptEngineSwitcher.ChakraCore.Native.linux-*", osArchitecture.ToString().ToLowerInvariant() ); descriptionBuilder.Append(" "); descriptionBuilder.AppendFormat(Strings.Engine_BuildNativeAssemblyForCurrentProcessorArchitecture, DllName.ForLinux, string.Format(buildInstructionsUrl, "linux") ); } } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { descriptionBuilder.AppendFormat(CoreStrings.Engine_AssemblyNotFound, DllName.ForOsx); descriptionBuilder.Append(" "); if (isMonoRuntime) { descriptionBuilder.AppendFormat(Strings.Engine_ManualInstallationUnderMonoRequired, "JavaScriptEngineSwitcher.ChakraCore.Native.osx-*", string.Format(manualInstallationInstructionsUrl, "os-x") ); } else { if (osArchitecture == Architecture.X64) { descriptionBuilder.AppendFormat(CoreStrings.Engine_NuGetPackageInstallationRequired, "JavaScriptEngineSwitcher.ChakraCore.Native.osx-x64"); } else { descriptionBuilder.AppendFormat(CoreStrings.Engine_NoNuGetPackageForProcessorArchitecture, "JavaScriptEngineSwitcher.ChakraCore.Native.osx-*", osArchitecture.ToString().ToLowerInvariant() ); descriptionBuilder.Append(" "); descriptionBuilder.AppendFormat(Strings.Engine_BuildNativeAssemblyForCurrentProcessorArchitecture, DllName.ForOsx, string.Format(buildInstructionsUrl, "os-x") ); } } } else { descriptionBuilder.Append(CoreStrings.Engine_OperatingSystemNotSupported); } description = descriptionBuilder.ToString(); stringBuilderPool.Return(descriptionBuilder); message = CoreErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName); } else { description = originalMessage; message = CoreErrorHelpers.GenerateEngineLoadErrorMessage(description, EngineName, true); } var wrapperEngineLoadException = new WrapperEngineLoadException(message, EngineName, EngineVersion, originalDllNotFoundException) { Description = description }; return(wrapperEngineLoadException); }
public async Task Handle_Aggregated_Exception() { // Act var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3)); // cancel task after 3 seconds var ct = cts.Token; string result = default; var tcExceptionWorksFlag = false; var dnfExceptionWorksFlag = false; var agExceptionWorksFlag = false; var baseExceptionWorksFlag = false; DllNotFoundException dllNotFoundException = default; TaskCanceledException taskCanceledException = default; // Action try { var stuff = new Stuff(); result = await stuff.SomeUnexcpectedFunc(ct); } catch (TaskCanceledException) { tcExceptionWorksFlag = true; } catch (DllNotFoundException) { dnfExceptionWorksFlag = true; } catch (AggregateException ae) when(ae.InnerException != null || ae.InnerExceptions.Count > 0) { agExceptionWorksFlag = true; // let's handle known inner exceptions ae.Handle(ex => { if (ex is DllNotFoundException dnfException) { dllNotFoundException = dnfException; return(true); } if (ex is TaskCanceledException tcException) { taskCanceledException = tcException; return(true); } // re-throw any unhandled exception return(false); }); } catch (Exception) { baseExceptionWorksFlag = true; } // Assert Assert.Null(result); Assert.NotNull(dllNotFoundException); Assert.NotNull(taskCanceledException); Assert.False(tcExceptionWorksFlag); Assert.True(agExceptionWorksFlag); Assert.False(dnfExceptionWorksFlag); Assert.False(baseExceptionWorksFlag); }
/// <summary> /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException. /// and in winrt and marshal APIs as Exception. /// </summary> /// <param name="errorCode"></param> /// <param name="message"></param> /// <param name="createCOMException"></param> /// <returns></returns> internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo) { if (errorCode >= 0) { return(null); } Exception exception = null; bool shouldDisplayHR = false; switch (errorCode) { case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException case __HResults.COR_E_ARITHMETIC: exception = new ArithmeticException(); break; case __HResults.COR_E_ARGUMENT: case unchecked ((int)0x800A01C1): case unchecked ((int)0x800A01C2): case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT: exception = new ArgumentException(); if (errorCode != __HResults.COR_E_ARGUMENT) { shouldDisplayHR = true; } break; case __HResults.E_BOUNDS: case __HResults.COR_E_ARGUMENTOUTOFRANGE: case __HResults.ERROR_NO_UNICODE_TRANSLATION: exception = new ArgumentOutOfRangeException(); if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE) { shouldDisplayHR = true; } break; case __HResults.COR_E_ARRAYTYPEMISMATCH: exception = new ArrayTypeMismatchException(); break; case __HResults.COR_E_BADIMAGEFORMAT: case __HResults.CLDB_E_FILE_OLDVER: case __HResults.CLDB_E_INDEX_NOTFOUND: case __HResults.CLDB_E_FILE_CORRUPT: case __HResults.COR_E_NEWER_RUNTIME: case __HResults.COR_E_ASSEMBLYEXPECTED: case __HResults.ERROR_BAD_EXE_FORMAT: case __HResults.ERROR_EXE_MARKED_INVALID: case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT: case __HResults.ERROR_NOACCESS: case __HResults.ERROR_INVALID_ORDINAL: case __HResults.ERROR_INVALID_DLL: case __HResults.ERROR_FILE_CORRUPT: case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY: case __HResults.META_E_BAD_SIGNATURE: exception = new BadImageFormatException(); // Always show HR for BadImageFormatException shouldDisplayHR = true; break; case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT: exception = new FormatException(); break; // CustomAttributeFormatException case __HResults.COR_E_DATAMISALIGNED: exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here? break; case __HResults.COR_E_DIVIDEBYZERO: case __HResults.CTL_E_DIVISIONBYZERO: exception = new DivideByZeroException(); if (errorCode != __HResults.COR_E_DIVIDEBYZERO) { shouldDisplayHR = true; } break; case __HResults.COR_E_DLLNOTFOUND: #if ENABLE_WINRT exception = new DllNotFoundException(); #endif break; case __HResults.COR_E_DUPLICATEWAITOBJECT: exception = new ArgumentException(); break; // DuplicateWaitObjectException case __HResults.COR_E_ENDOFSTREAM: case unchecked ((int)0x800A003E): exception = new CoreFX_IO::System.IO.EndOfStreamException(); if (errorCode != __HResults.COR_E_ENDOFSTREAM) { shouldDisplayHR = true; } break; case __HResults.COR_E_TYPEACCESS: // TypeAccessException case __HResults.COR_E_ENTRYPOINTNOTFOUND: exception = new TypeLoadException(); break; // EntryPointNotFoundException case __HResults.COR_E_EXCEPTION: exception = new Exception(); break; case __HResults.COR_E_DIRECTORYNOTFOUND: case __HResults.STG_E_PATHNOTFOUND: case __HResults.CTL_E_PATHNOTFOUND: exception = new System.IO.DirectoryNotFoundException(); if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND) { shouldDisplayHR = true; } break; case __HResults.COR_E_FILELOAD: case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION: case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED: case __HResults.FUSION_E_LOADFROM_BLOCKED: case __HResults.FUSION_E_CACHEFILE_FAILED: case __HResults.FUSION_E_ASM_MODULE_MISSING: case __HResults.FUSION_E_INVALID_NAME: case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED: case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH: case __HResults.COR_E_MODULE_HASH_CHECK_FAILED: case __HResults.FUSION_E_REF_DEF_MISMATCH: case __HResults.SECURITY_E_INCOMPATIBLE_SHARE: case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE: case __HResults.SECURITY_E_UNVERIFIABLE: case __HResults.COR_E_FIXUPSINEXE: case __HResults.ERROR_TOO_MANY_OPEN_FILES: case __HResults.ERROR_SHARING_VIOLATION: case __HResults.ERROR_LOCK_VIOLATION: case __HResults.ERROR_OPEN_FAILED: case __HResults.ERROR_DISK_CORRUPT: case __HResults.ERROR_UNRECOGNIZED_VOLUME: case __HResults.ERROR_DLL_INIT_FAILED: case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED: case __HResults.CORSEC_E_MISSING_STRONGNAME: case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS: case __HResults.ERROR_FILE_INVALID: exception = new System.IO.FileLoadException(); shouldDisplayHR = true; break; case __HResults.COR_E_PATHTOOLONG: exception = new System.IO.PathTooLongException(); break; case __HResults.COR_E_IO: case __HResults.CTL_E_DEVICEIOERROR: case unchecked ((int)0x800A793C): case unchecked ((int)0x800A793D): exception = new System.IO.IOException(); if (errorCode != __HResults.COR_E_IO) { shouldDisplayHR = true; } break; case __HResults.ERROR_FILE_NOT_FOUND: case __HResults.ERROR_MOD_NOT_FOUND: case __HResults.ERROR_INVALID_NAME: case __HResults.CTL_E_FILENOTFOUND: case __HResults.ERROR_BAD_NET_NAME: case __HResults.ERROR_BAD_NETPATH: case __HResults.ERROR_NOT_READY: case __HResults.ERROR_WRONG_TARGET_NAME: case __HResults.INET_E_UNKNOWN_PROTOCOL: case __HResults.INET_E_CONNECTION_TIMEOUT: case __HResults.INET_E_CANNOT_CONNECT: case __HResults.INET_E_RESOURCE_NOT_FOUND: case __HResults.INET_E_OBJECT_NOT_FOUND: case __HResults.INET_E_DOWNLOAD_FAILURE: case __HResults.INET_E_DATA_NOT_AVAILABLE: case __HResults.ERROR_DLL_NOT_FOUND: case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW: case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH: case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND: exception = new System.IO.FileNotFoundException(); shouldDisplayHR = true; break; case __HResults.COR_E_FORMAT: exception = new FormatException(); break; case __HResults.COR_E_INDEXOUTOFRANGE: case unchecked ((int)0x800a0009): exception = new IndexOutOfRangeException(); if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE) { shouldDisplayHR = true; } break; case __HResults.COR_E_INVALIDCAST: exception = new InvalidCastException(); break; case __HResults.COR_E_INVALIDCOMOBJECT: exception = new InvalidComObjectException(); break; case __HResults.COR_E_INVALIDOLEVARIANTTYPE: exception = new InvalidOleVariantTypeException(); break; case __HResults.COR_E_INVALIDOPERATION: case __HResults.E_ILLEGAL_STATE_CHANGE: case __HResults.E_ILLEGAL_METHOD_CALL: case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT: case __HResults.APPMODEL_ERROR_NO_PACKAGE: exception = new InvalidOperationException(); if (errorCode != __HResults.COR_E_INVALIDOPERATION) { shouldDisplayHR = true; } break; case __HResults.COR_E_MARSHALDIRECTIVE: exception = new MarshalDirectiveException(); break; case __HResults.COR_E_METHODACCESS: // MethodAccessException case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException case __HResults.COR_E_FIELDACCESS: case __HResults.COR_E_MEMBERACCESS: exception = new MemberAccessException(); if (errorCode != __HResults.COR_E_METHODACCESS) { shouldDisplayHR = true; } break; case __HResults.COR_E_MISSINGFIELD: // MissingFieldException case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException case __HResults.COR_E_MISSINGMEMBER: case unchecked ((int)0x800A01CD): exception = new MissingMemberException(); break; case __HResults.COR_E_MISSINGMANIFESTRESOURCE: exception = new System.Resources.MissingManifestResourceException(); break; case __HResults.COR_E_NOTSUPPORTED: case unchecked ((int)0x800A01B6): case unchecked ((int)0x800A01BD): case unchecked ((int)0x800A01CA): case unchecked ((int)0x800A01CB): exception = new NotSupportedException(); if (errorCode != __HResults.COR_E_NOTSUPPORTED) { shouldDisplayHR = true; } break; case __HResults.COR_E_NULLREFERENCE: exception = new NullReferenceException(); break; case __HResults.COR_E_OBJECTDISPOSED: case __HResults.RO_E_CLOSED: // No default constructor exception = new ObjectDisposedException(String.Empty); break; case __HResults.COR_E_OPERATIONCANCELED: #if ENABLE_WINRT exception = new OperationCanceledException(); #endif break; case __HResults.COR_E_OVERFLOW: case __HResults.CTL_E_OVERFLOW: exception = new OverflowException(); break; case __HResults.COR_E_PLATFORMNOTSUPPORTED: exception = new PlatformNotSupportedException(message); break; case __HResults.COR_E_RANK: exception = new RankException(); break; case __HResults.COR_E_REFLECTIONTYPELOAD: #if ENABLE_WINRT exception = new System.Reflection.ReflectionTypeLoadException(null, null); #endif break; case __HResults.COR_E_SECURITY: case __HResults.CORSEC_E_INVALID_STRONGNAME: case __HResults.CTL_E_PERMISSIONDENIED: case unchecked ((int)0x800A01A3): case __HResults.CORSEC_E_INVALID_PUBLICKEY: case __HResults.CORSEC_E_SIGNATURE_MISMATCH: exception = new System.Security.SecurityException(); break; case __HResults.COR_E_SAFEARRAYRANKMISMATCH: exception = new SafeArrayRankMismatchException(); break; case __HResults.COR_E_SAFEARRAYTYPEMISMATCH: exception = new SafeArrayTypeMismatchException(); break; case __HResults.COR_E_SERIALIZATION: exception = new System.Runtime.Serialization.SerializationException(message); break; case __HResults.COR_E_SYNCHRONIZATIONLOCK: exception = new System.Threading.SynchronizationLockException(); break; case __HResults.COR_E_TARGETINVOCATION: exception = new System.Reflection.TargetInvocationException(null); break; case __HResults.COR_E_TARGETPARAMCOUNT: exception = new System.Reflection.TargetParameterCountException(); break; case __HResults.COR_E_TYPEINITIALIZATION: exception = InteropExtensions.CreateTypeInitializationException(message); break; case __HResults.COR_E_TYPELOAD: case __HResults.RO_E_METADATA_NAME_NOT_FOUND: case __HResults.CLR_E_BIND_TYPE_NOT_FOUND: exception = new TypeLoadException(); if (errorCode != __HResults.COR_E_TYPELOAD) { shouldDisplayHR = true; } break; case __HResults.COR_E_UNAUTHORIZEDACCESS: case __HResults.CTL_E_PATHFILEACCESSERROR: case unchecked ((int)0x800A014F): exception = new UnauthorizedAccessException(); shouldDisplayHR = true; break; case __HResults.COR_E_VERIFICATION: exception = new System.Security.VerificationException(); break; case __HResults.E_NOTIMPL: exception = new NotImplementedException(); break; case __HResults.E_OUTOFMEMORY: case __HResults.CTL_E_OUTOFMEMORY: case unchecked ((int)0x800A7919): exception = new OutOfMemoryException(); if (errorCode != __HResults.E_OUTOFMEMORY) { shouldDisplayHR = true; } break; #if ENABLE_WINRT case __HResults.E_XAMLPARSEFAILED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTAVAILABLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_ELEMENTNOTENABLED: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; case __HResults.E_LAYOUTCYCLE: exception = ConstructExceptionUsingReflection( "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", message); break; #endif // ENABLE_WINRT case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException case __HResults.COR_E_APPLICATION: // ApplicationException case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException case __HResults.COR_E_CODECONTRACTFAILED: // ContractException case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException case __HResults.CORSEC_E_CRYPTO: // CryptographicException case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException case __HResults.COR_E_REMOTING: // RemotingException case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException case __HResults.COR_E_SERVER: // ServerException case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException case __HResults.COR_E_SYSTEM: // SystemException case __HResults.COR_E_TARGET: // TargetException case __HResults.COR_E_THREADABORTED: // TargetException case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException case __HResults.COR_E_THREADSTATE: // ThreadStateException case __HResults.COR_E_THREADSTART: // ThreadStartException case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException case __HResults.ISS_E_CALLER: // IsolatedStorageException case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException case __HResults.ISS_E_MACHINE: // IsolatedStorageException case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException case __HResults.E_FAIL: default: break; } if (exception == null) { if (createCOMException) { exception = new COMException(); if (errorCode != __HResults.E_FAIL) { shouldDisplayHR = true; } } else { exception = new Exception(); if (errorCode != __HResults.COR_E_EXCEPTION) { shouldDisplayHR = true; } } } bool shouldConstructMessage = false; if (hasErrorInfo) { // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if // the message is not available and do not use the shouldDisplayHR setting if (message == null) { shouldConstructMessage = true; } } else { // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above shouldConstructMessage = shouldDisplayHR; } if (shouldConstructMessage) { // // Append the HR into error message, just in case the app wants to look at the HR in // message to determine behavior. We didn't expose HResult property until v4.5 and // GetHRFromException has side effects so probably Message was their only choice. // This behavior is probably not exactly the same as in desktop but it is fine to append // more message at the end. In any case, having the HR in the error message are helpful // to developers. // This makes sure: // 1. We always have a HR 0xNNNNNNNN in the message // 2. Put in a nice "Exception thrown from HRESULT" message if we can // 3. Wrap it in () if there is an existing message // // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString()); message = ExternalInterop.GetMessage(errorCode); // Always make sure we have at least the HRESULT part in retail build or when the message // is empty. if (message == null) { message = hrMessage; } else { message = message + " (" + hrMessage + ")"; } } if (message != null) { // Set message explicitly rather than calling constructor because certain ctors would append a // prefix to the message and that is not what we want InteropExtensions.SetExceptionMessage(exception, message); } InteropExtensions.SetExceptionErrorCode(exception, errorCode); return(exception); }