Here are the examples of the csharp api System.Exception.GetType() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2324 Examples
19
View Source File : ChatCommands.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public DataChat? Error(Exception e) {
string cmdName = Cmd?.ID ?? "?";
if (e.GetType() == typeof(Exception)) {
Logger.Log(LogLevel.VVV, "chatcmd", $"Command {cmdName} failed:\n{e}");
return Send($"Command {cmdName} failed: {e.Message}", color: Chat.Settings.ColorError);
}
Logger.Log(LogLevel.ERR, "chatcmd", $"Command {cmdName} failed:\n{e}");
return Send($"Command {cmdName} failed due to an internal error.", color: Chat.Settings.ColorError);
}
19
View Source File : patch_Program.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static void LogDetailed(Exception e, string tag = null) {
for (Exception e_ = e; e_ != null; e_ = e_.InnerException) {
Console.WriteLine(e_.GetType().FullName + ": " + e_.Message + "\n" + e_.StackTrace);
if (e_ is ReflectionTypeLoadException) {
ReflectionTypeLoadException rtle = (ReflectionTypeLoadException) e_;
for (int i = 0; i < rtle.Types.Length; i++) {
Console.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + rtle.Types[i]);
}
for (int i = 0; i < rtle.LoaderExceptions.Length; i++) {
LogDetailed(rtle.LoaderExceptions[i], tag + (tag == null ? "" : ", ") + "rtle:" + i);
}
}
if (e_ is TypeLoadException) {
Console.WriteLine("TypeLoadException.TypeName: " + ((TypeLoadException) e_).TypeName);
}
if (e_ is BadImageFormatException) {
Console.WriteLine("BadImageFormatException.FileName: " + ((BadImageFormatException) e_).FileName);
}
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5
License : GNU General Public License v3.0
Project Creator : 0x2b00b1e5
static void Main(string[] args)
{
Console.WriteLine("Running...");
try
{
FL_RPC.Init();
}
catch (Exception e)
{
Console.WriteLine("\n \nERROR: " + e.Message);
Console.WriteLine("INFO: Exception Name: " + e.GetType());
Console.WriteLine("\n");
FL_RPC.StopAndExit();
Environment.Exit(-1);
}
}
19
View Source File : Program.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
static string GetExceptionMsg(Exception ex, string backStr)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("****************************异常文本****************************");
sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
if (ex != null)
{
sb.AppendLine("【异常类型】:" + ex.GetType().Name);
sb.AppendLine("【异常信息】:" + ex.Message);
sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
}
else
{
sb.AppendLine("【未处理异常】:" + backStr);
}
sb.AppendLine("***************************************************************");
return sb.ToString();
}
19
View Source File : TransformCopyTest.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
private void replacedertObjectsEqual(object a, object b) {
if ((a == null) != (b == null)) {
replacedert.Fail("One object was null an the other was not.");
return;
}
Type typeA = a.GetType();
Type typeB = b.GetType();
if (typeA != typeB) {
replacedert.Fail("Type " + typeA + " is not equal to type " + typeB + ".");
}
if (typeA.IsValueType) {
replacedert.That(a, Is.EqualTo(b));
return;
}
if (a is IList) {
IList aList = a as IList;
IList bList = b as IList;
replacedert.That(aList.Count, Is.EqualTo(bList.Count));
for (int i = 0; i < aList.Count; i++) {
replacedertObjectsEqual(aList[i], bList[i]);
}
} else {
FieldInfo[] fields = typeA.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields) {
replacedertObjectsEqual(field.GetValue(a), field.GetValue(b));
}
PropertyInfo[] properties = typeA.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties) {
if (property.GetIndexParameters().Length == 0) {
object propA;
try {
propA = property.GetValue(a, null);
} catch (Exception exceptionA) {
try {
property.GetValue(b, null);
replacedert.Fail("One property threw an exception where the other did not.");
return;
} catch (Exception exceptionB) {
replacedert.That(exceptionA.GetType(), Is.EqualTo(exceptionB.GetType()), "Both properties threw exceptions but their types were different.");
return;
}
}
object propB = property.GetValue(b, null);
replacedertObjectsEqual(propA, propB);
}
}
}
}
19
View Source File : TaskExtensionTest.cs
License : MIT License
Project Creator : 5argon
License : MIT License
Project Creator : 5argon
public static async Task ShouldThrow<T>(this Task asyncMethod, string message) where T : Exception
{
try
{
await asyncMethod; //Should throw..
}
catch (T)
{
//Task should throw Aggregate but add this just in case.
Debug.Log("Caught an exception : " + typeof(T).FullName + " !!");
return;
}
catch (AggregateException ag)
{
foreach (Exception e in ag.InnerExceptions)
{
Debug.Log("Caught an exception : " + e.GetType().FullName + " !!");
if (message != "")
{
//Fails here if we find any other inner exceptions
replacedert.That(e, Is.TypeOf<T>(), message + " | " + e.ToString());
}
else
{
//Fails here also
replacedert.That(e, Is.TypeOf<T>(), e.ToString() + " " + "An exception should be of type " + typeof(T).FullName);
}
}
return;
}
replacedert.Fail("Expected an exception of type " + typeof(T).FullName + " but no exception was thrown.");
}
19
View Source File : GlobalExceptions.cs
License : Apache License 2.0
Project Creator : 91270
License : Apache License 2.0
Project Creator : 91270
public string WriteLog(string throwMsg, Exception ex)
{
return $"\r\n【自定义错误】:{throwMsg} \r\n【异常类型】:{ex.GetType().Name} \r\n【异常信息】:{ex.Message} \r\n【堆栈调用】:{ex.StackTrace }\r\n";
}
19
View Source File : RtmpServer.cs
License : MIT License
Project Creator : a1q123456
License : MIT License
Project Creator : a1q123456
private async void AcceptCallback(IAsyncResult ar, CancellationToken ct)
{
Socket listener = (Socket)ar.AsyncState;
Socket client = listener.EndAccept(ar);
client.NoDelay = true;
// Signal the main thread to continue.
_allDone.Set();
IOPipeLine pipe = null;
try
{
pipe = new IOPipeLine(client, _options);
await pipe.StartAsync(ct);
}
catch (TimeoutException)
{
client.Close();
}
catch (Exception e)
{
Console.WriteLine("{0} Message: {1}", e.GetType().ToString(), e.Message);
Console.WriteLine(e.StackTrace);
client.Close();
}
finally
{
pipe?.Dispose();
}
}
19
View Source File : Logger.cs
License : MIT License
Project Creator : aabiryukov
License : MIT License
Project Creator : aabiryukov
private static string FormatExceptionText(Exception exception)
{
return $"EXCEPTION [{exception.GetType()}]: {exception.ToString()}";
}
19
View Source File : ExceptionUtil.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string ExceptionLog(Exception e, string local)
{
var msg = local + " " + e.Message
+ (e.InnerException == null ? "" : " -> " + e.InnerException.Message)
+ Environment.NewLine
+ " (" + (e.InnerException != null ? e.InnerException : e).GetType().Name + ") "
+ (e.InnerException != null && e.InnerException.StackTrace != null ? e.InnerException.StackTrace : e.StackTrace);
Loger.Log(msg);
return msg;
}
19
View Source File : DellFanManagementApp.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
[STAThread]
static int Main(string[] args)
{
if (args.Length == 0)
{
// GUI mode.
try
{
if (UacHelper.IsProcessElevated())
{
// Looks like we're ready to start up the GUI app.
// Set process priority to high.
Process.GetCurrentProcess().PriorityClreplaced = ProcessPriorityClreplaced.High;
// Boilerplate code to start the app.
Application.SetHighDpiMode(HighDpiMode.DpiUnaware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DellFanManagementGuiForm());
}
else
{
MessageBox.Show("This program must be run with administrative privileges.", "Dell Fan Management privilege check", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception exception)
{
MessageBox.Show(string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace),
"Error starting application", MessageBoxButtons.OK, MessageBoxIcon.Error);
return 1;
}
return 0;
}
else
{
// CMD mode.
try
{
Console.WriteLine("Dell Fan Management, version {0}", Version);
Console.WriteLine("By Aaron Kelley");
Console.WriteLine("Licensed under GPLv3");
Console.WriteLine("Source code available at https://github.com/AaronKelley/DellFanManagement");
Console.WriteLine();
if (UacHelper.IsProcessElevated())
{
if (args[0].ToLower() == "packagetest")
{
return PackageTest.RunPackageTests() ? 0 : 1;
}
else if (args[0].ToLower() == "setthermalsetting")
{
return SetThermalSetting.ExecuteSetThermalSetting(args);
}
else if (args[0].ToLower() == "smi-token-dump")
{
return SmiTokenDump();
}
else if (args[0].ToLower() == "smi-get-token")
{
return SmiGetToken(args);
}
else if (args[0].ToLower() == "smi-set-token")
{
return SmiSetToken(args);
}
else
{
Console.WriteLine("Dell SMM I/O driver by 424778940z");
Console.WriteLine("https://github.com/424778940z/bzh-windrv-dell-smm-io");
Console.WriteLine();
Console.WriteLine("Derived from \"Dell fan utility\" by 424778940z");
Console.WriteLine("https://github.com/424778940z/dell-fan-utility");
Console.WriteLine();
return DellFanCmd.ProcessCommand(args);
}
}
else
{
Console.WriteLine();
Console.WriteLine("This program must be run with administrative privileges.");
return 1;
}
}
catch (Exception exception)
{
Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
return 1;
}
}
}
19
View Source File : PackageTest.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static bool DellSmbiosBzhTest()
{
try
{
Console.WriteLine("Running DellSmbiosBzhLib test.");
if (!DellSmbiosBzh.Initialize())
{
Console.WriteLine(" Failed to load driver.");
return false;
}
uint? result = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);
Console.WriteLine(" Fan 1 RPM: {0}", result);
DellSmbiosBzh.Shutdown();
}
catch (Exception exception)
{
Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
return false;
}
Console.WriteLine(" ...Preplaceded.");
return true;
}
19
View Source File : PackageTest.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static bool DellSmbiosSmiTest()
{
try
{
Console.WriteLine("Running DellSmbiosSmiLib test.");
ThermalSetting currentSetting = DellSmbiosSmi.GetThermalSetting();
Console.WriteLine("Thermal setting: {0}", currentSetting);
}
catch (Exception exception)
{
Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
return false;
}
Console.WriteLine(" ...Preplaceded.");
return true;
}
19
View Source File : PackageTest.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static bool IrrKlangTest()
{
try
{
Console.WriteLine("Running irrKlang test.");
new SoundPlayer().PlaySound(@"C:\Windows\Media\Windows Logon.wav");
foreach (AudioDevice audioDevice in Utility.GetAudioDevices())
{
Console.WriteLine(" {0}: {1}", audioDevice.DeviceId, audioDevice.DeviceName);
}
}
catch (Exception exception)
{
Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
return false;
}
Console.WriteLine(" ...Preplaceded.");
return true;
}
19
View Source File : Core.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private void BackgroundThread()
{
_state.WaitOne();
_state.BackgroundThreadRunning = true;
_state.Release();
bool releaseSemapreplaced = false;
try
{
if (_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
{
_fanController.EnableAutomaticFanControl();
Log.Write("Enabled EC fan control – startup");
}
while (_state.BackgroundThreadRunning)
{
_state.WaitOne();
_requestSemapreplaced.WaitOne();
releaseSemapreplaced = true;
// Update state.
_state.Update();
// Take action based on configuration.
if (_state.OperationMode == OperationMode.Automatic)
{
if (!_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
{
_state.EcFanControlEnabled = true;
_fanController.EnableAutomaticFanControl();
Log.Write("Enabled EC fan control – automatic mode");
}
}
else if (_state.OperationMode == OperationMode.Manual && IsAutomaticFanControlDisableSupported && IsSpecificFanControlSupported)
{
// Check for EC control state changes that need to be applied.
if (_ecFanControlRequested && !_state.EcFanControlEnabled)
{
_state.EcFanControlEnabled = true;
_fanController.EnableAutomaticFanControl();
Log.Write("Enabled EC fan control – manual mode");
_state.Fan1Level = null;
_state.Fan2Level = null;
_fan1LevelRequested = null;
_fan2LevelRequested = null;
}
else if (!_ecFanControlRequested && _state.EcFanControlEnabled)
{
_state.EcFanControlEnabled = false;
_fanController.DisableAutomaticFanControl();
Log.Write("Disabled EC fan control – manual mode");
}
// Check for fan control state changes that need to be applied.
if (!_state.EcFanControlEnabled)
{
if (_state.Fan1Level != _fan1LevelRequested)
{
_state.Fan1Level = _fan1LevelRequested;
if (_fan1LevelRequested != null)
{
_fanController.SetFanLevel((FanLevel)_fan1LevelRequested, IsIndividualFanControlSupported ? FanIndex.Fan1 : FanIndex.AllFans);
}
}
if (_state.Fan2Present && IsIndividualFanControlSupported && _state.Fan2Level != _fan2LevelRequested)
{
_state.Fan2Level = _fan2LevelRequested;
if (_fan2LevelRequested != null)
{
_fanController.SetFanLevel((FanLevel)_fan2LevelRequested, FanIndex.Fan2);
}
}
}
// Warn if a fan is set to completely off.
if (!_state.EcFanControlEnabled && (_state.Fan1Level == FanLevel.Off || (_state.Fan2Present && _state.Fan2Level == FanLevel.Off)))
{
_state.ConsistencyModeStatus = "Warning: Fans set to \"off\" will not turn on regardless of temperature or load on the system";
}
else
{
_state.ConsistencyModeStatus = " ";
}
}
else if (_state.OperationMode == OperationMode.Consistency && IsAutomaticFanControlDisableSupported)
{
// Consistency mode logic.
ConsistencyModeLogic();
}
// See if we need to update the BIOS thermal setting.
if (_state.ThermalSetting != ThermalSetting.Error && RequestedThermalSetting != _state.ThermalSetting)
{
DellSmbiosSmi.SetThermalSetting((ThermalSetting)RequestedThermalSetting);
_state.UpdateThermalSetting();
}
// Check to see if the active audio device has disappeared.
if (_state.AudioThreadRunning && !_state.AudioDevices.Contains(_state.SelectedAudioDevice))
{
// Remember the audio device in case it reappears.
_state.BringBackAudioDevice = _state.SelectedAudioDevice;
// Terminate the audio thread.
_soundPlayer?.RequestTermination();
}
_requestSemapreplaced.Release();
_state.Release();
releaseSemapreplaced = false;
UpdateForm();
Thread.Sleep(Core.RefreshInterval);
}
// If we got out of the loop without error, the program is terminating.
if (IsAutomaticFanControlDisableSupported)
{
_fanController.EnableAutomaticFanControl();
Log.Write("Enabled EC fan control – shutdown");
}
// Clean up as the program terminates.
_fanController.Shutdown();
}
catch (Exception exception)
{
if (releaseSemapreplaced)
{
_state.Release();
}
_state.WaitOne();
_state.Error = string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
_state.Release();
Log.Write(_state.Error);
}
_state.WaitOne();
_state.BackgroundThreadRunning = false;
_state.Release();
UpdateForm();
}
19
View Source File : Log.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
public static void Write(Exception exception)
{
Write(string.Format("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace));
}
19
View Source File : PackageTest.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static bool OpenHardwareMonitorTest()
{
try
{
Console.WriteLine("Running Open Hardware Monitor test.");
Computer computer = new()
{
IsCpuEnabled = true
};
computer.Open();
foreach (IHardware hardware in computer.Hardware)
{
hardware.Update();
foreach (ISensor sensor in hardware.Sensors)
{
if (sensor.SensorType == SensorType.Temperature && sensor.Value.HasValue)
{
Console.WriteLine(" {0}: {1}", sensor.Name, sensor.Value);
}
}
}
}
catch (Exception exception)
{
Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
return false;
}
Console.WriteLine(" ...Preplaceded.");
return true;
}
19
View Source File : PackageTest.cs
License : GNU General Public License v3.0
Project Creator : AaronKelley
License : GNU General Public License v3.0
Project Creator : AaronKelley
private static bool NvapiTest()
{
bool foundGpu = false;
try
{
Console.WriteLine("Running NVAPI test.");
foreach (PhysicalGPU gpu in PhysicalGPU.GetPhysicalGPUs())
{
Console.WriteLine(" Found GPU: {0}", gpu.FullName);
foundGpu = true;
try
{
foreach (GPUThermalSensor sensor in gpu.ThermalInformation.ThermalSensors)
{
Console.WriteLine(" Current GPU temperature: {0}", sensor.CurrentTemperature);
}
}
catch (NVIDIAApiException exception)
{
if (exception.Message == "NVAPI_GPU_NOT_POWERED")
{
Console.WriteLine(" GPU is currently powered off.");
}
else
{
throw;
}
}
}
}
catch (Exception exception)
{
Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
return false;
}
Console.WriteLine(" ...Preplaceded.");
if (!foundGpu)
{
Console.WriteLine(" (Note: No NVIDIA GPUs found.)");
}
return true;
}
19
View Source File : BaseDataProviderAccessCoreSystem.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private bool RegisterDataProviderInternal<T>(
bool retryWithRegistrar,
Type concreteType,
SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
params object[] args) where T : IMixedRealityDataProvider
{
#if !UNITY_EDITOR
if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#else
if (!EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#endif
{
return false;
}
if (concreteType == null)
{
Debug.LogError($"Unable to register {typeof(T).Name} service with a null concrete type.");
return false;
}
if (!typeof(IMixedRealityDataProvider).IsreplacedignableFrom(concreteType))
{
Debug.LogError($"Unable to register the {concreteType.Name} data provider. It does not implement {typeof(IMixedRealityDataProvider)}.");
return false;
}
T dataProviderInstance;
try
{
dataProviderInstance = (T)Activator.CreateInstance(concreteType, args);
}
catch (Exception e)
{
if (retryWithRegistrar && (e is MissingMethodException))
{
Debug.LogWarning($"Failed to find an appropriate constructor for the {concreteType.Name} data provider. Adding the Registrar instance and re-attempting registration.");
#pragma warning disable 0618
List<object> updatedArgs = new List<object>();
updatedArgs.Add(Registrar);
if (args != null)
{
updatedArgs.AddRange(args);
}
return RegisterDataProviderInternal<T>(
false, // Do NOT retry, we have already added the configured IMIxedRealityServiceRegistrar
concreteType,
supportedPlatforms,
updatedArgs.ToArray());
#pragma warning restore 0618
}
Debug.LogError($"Failed to register the {concreteType.Name} data provider: {e.GetType()} - {e.Message}");
// Failures to create the concrete type generally surface as nested exceptions - just logging
// the top level exception itself may not be helpful. If there is a nested exception (for example,
// null reference in the constructor of the object itself), it's helpful to also surface those here.
if (e.InnerException != null)
{
Debug.LogError("Underlying exception information: " + e.InnerException);
}
return false;
}
return RegisterDataProvider(dataProviderInstance);
}
19
View Source File : BaseServiceManager.cs
License : Apache License 2.0
Project Creator : abist-co-ltd
License : Apache License 2.0
Project Creator : abist-co-ltd
private T ActivateInstance<T>(Type concreteType, SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1), params object[] args) where T : IMixedRealityService
{
if (concreteType == null) { return default(T); }
#if UNITY_EDITOR
if (!UnityEditor.EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#else
if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#endif
{
return default(T);
}
if (!typeof(T).IsreplacedignableFrom(concreteType))
{
Debug.LogError($"Error: {concreteType.Name} service must implement {typeof(T)}.");
return default(T);
}
try
{
T serviceInstance = (T)Activator.CreateInstance(concreteType, args);
return serviceInstance;
}
catch (Exception e)
{
Debug.LogError($"Error: Failed to instantiate {concreteType.Name}: {e.GetType()} - {e.Message}");
return default(T);
}
}
19
View Source File : ExceptionView.xaml.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void LogException(Exception exception)
{
if (exception == null) return;
exceptionViewer.Text += exception.GetType().Name + ": " + exception.Message + Environment.NewLine;
exceptionViewer.Text += "-------------------------------------------" + Environment.NewLine + Environment.NewLine;
exceptionViewer.Text += "Stack Trace: " + Environment.NewLine;
exceptionViewer.Text += exception.StackTrace + Environment.NewLine + Environment.NewLine;
LogException(exception.InnerException);
}
19
View Source File : JobServer.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private async Task CheckNetworkEndpointsAsync(int attemptsLeft)
{
try
{
Trace.Info("Requesting Actions Service health endpoint status");
using (var httpClientHandler = HostContext.CreateHttpClientHandler())
using (var actionsClient = new HttpClient(httpClientHandler))
{
var baseUri = new Uri(_connection.Uri.GetLeftPart(UriPartial.Authority));
actionsClient.DefaultRequestHeaders.UserAgent.AddRange(HostContext.UserAgents);
// Call the _apis/health endpoint, and include how many attempts are left as a URL query for easy tracking
var response = await actionsClient.GetAsync(new Uri(baseUri, $"_apis/health?_internalRunnerAttemptsLeft={attemptsLeft}"));
Trace.Info($"Actions health status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
// Log error, but continue as this call is best-effort
Trace.Info($"Actions Service health endpoint failed due to {ex.GetType().Name}");
Trace.Error(ex);
}
try
{
Trace.Info("Requesting Github API endpoint status");
// This is a dotcom public API... just call it directly
using (var httpClientHandler = HostContext.CreateHttpClientHandler())
using (var gitHubClient = new HttpClient(httpClientHandler))
{
gitHubClient.DefaultRequestHeaders.UserAgent.AddRange(HostContext.UserAgents);
// Call the api.github.com endpoint, and include how many attempts are left as a URL query for easy tracking
var response = await gitHubClient.GetAsync($"https://api.github.com?_internalRunnerAttemptsLeft={attemptsLeft}");
Trace.Info($"api.github.com status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
// Log error, but continue as this call is best-effort
Trace.Info($"Github API endpoint failed due to {ex.GetType().Name}");
Trace.Error(ex);
}
}
19
View Source File : VssNetworkHelper.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static bool IsTransientNetworkExceptionHelper(
Exception ex,
VssHttpRetryOptions options,
out HttpStatusCode? httpStatusCode,
out WebExceptionStatus? webExceptionStatus,
out SocketError? socketErrorCode,
out WinHttpErrorCode? winHttpErrorCode,
out CurlErrorCode? curlErrorCode)
{
ArgumentUtility.CheckForNull(ex, "ex");
httpStatusCode = null;
webExceptionStatus = null;
socketErrorCode = null;
winHttpErrorCode = null;
curlErrorCode = null;
if (ex is WebException)
{
WebException webEx = (WebException)ex;
if (webEx.Response != null && webEx.Response is HttpWebResponse)
{
var httpResponse = (HttpWebResponse)webEx.Response;
httpStatusCode = httpResponse.StatusCode;
// If the options include this status code as a retryable error then we report the exception
// as transient to the caller
if (options.RetryableStatusCodes.Contains(httpResponse.StatusCode))
{
return true;
}
}
webExceptionStatus = webEx.Status;
if (webEx.Status == WebExceptionStatus.ConnectFailure ||
webEx.Status == WebExceptionStatus.ConnectionClosed ||
webEx.Status == WebExceptionStatus.KeepAliveFailure ||
webEx.Status == WebExceptionStatus.NameResolutionFailure ||
webEx.Status == WebExceptionStatus.ReceiveFailure ||
webEx.Status == WebExceptionStatus.SendFailure ||
webEx.Status == WebExceptionStatus.Timeout)
{
return true;
}
}
else if (ex is SocketException)
{
SocketException sockEx = (SocketException)ex;
socketErrorCode = sockEx.SocketErrorCode;
if (sockEx.SocketErrorCode == SocketError.Interrupted ||
sockEx.SocketErrorCode == SocketError.NetworkDown ||
sockEx.SocketErrorCode == SocketError.NetworkUnreachable ||
sockEx.SocketErrorCode == SocketError.NetworkReset ||
sockEx.SocketErrorCode == SocketError.ConnectionAborted ||
sockEx.SocketErrorCode == SocketError.ConnectionReset ||
sockEx.SocketErrorCode == SocketError.TimedOut ||
sockEx.SocketErrorCode == SocketError.HostDown ||
sockEx.SocketErrorCode == SocketError.HostUnreachable ||
sockEx.SocketErrorCode == SocketError.TryAgain)
{
return true;
}
}
else if (ex is Win32Exception) // WinHttpException when use WinHttp (dotnet core)
{
Win32Exception winHttpEx = (Win32Exception)ex;
Int32 errorCode = winHttpEx.NativeErrorCode;
if (errorCode > (Int32)WinHttpErrorCode.WINHTTP_ERROR_BASE &&
errorCode <= (Int32)WinHttpErrorCode.WINHTTP_ERROR_LAST)
{
winHttpErrorCode = (WinHttpErrorCode)errorCode;
if (winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_CANNOT_CONNECT ||
winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_CONNECTION_ERROR ||
winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_INTERNAL_ERROR ||
winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_NAME_NOT_RESOLVED ||
winHttpErrorCode == WinHttpErrorCode.ERROR_WINHTTP_TIMEOUT)
{
return true;
}
}
}
else if (ex is IOException)
{
if (null != ex.InnerException &&
ex.InnerException is Win32Exception)
{
String stackTrace = ex.StackTrace;
if (null != stackTrace &&
stackTrace.IndexOf("System.Net.Security._SslStream.StartWriting(", StringComparison.Ordinal) >= 0)
{
// HACK: There is an underlying HRESULT code for this error which is not set on the exception which
// bubbles from the underlying stack. The top of the stack trace will be in the _SslStream clreplaced
// and will have an exception chain of HttpRequestException -> IOException -> Win32Exception.
// Check for SEC_E_CONTEXT_EXPIRED as this occurs at random in the underlying stack. Retrying the
// request should get a new connection and work correctly, so we ignore this particular error.
return true;
}
}
}
else if (ex.GetType().Name == "CurlException") // CurlException when use libcurl (dotnet core)
{
// Valid curl error code should in range (0, 93]
if (ex.HResult > 0 && ex.HResult < 94)
{
curlErrorCode = (CurlErrorCode)ex.HResult;
if (curlErrorCode == CurlErrorCode.CURLE_COULDNT_RESOLVE_PROXY ||
curlErrorCode == CurlErrorCode.CURLE_COULDNT_RESOLVE_HOST ||
curlErrorCode == CurlErrorCode.CURLE_COULDNT_CONNECT ||
curlErrorCode == CurlErrorCode.CURLE_HTTP2 ||
curlErrorCode == CurlErrorCode.CURLE_PARTIAL_FILE ||
curlErrorCode == CurlErrorCode.CURLE_WRITE_ERROR ||
curlErrorCode == CurlErrorCode.CURLE_UPLOAD_FAILED ||
curlErrorCode == CurlErrorCode.CURLE_READ_ERROR ||
curlErrorCode == CurlErrorCode.CURLE_OPERATION_TIMEDOUT ||
curlErrorCode == CurlErrorCode.CURLE_INTERFACE_FAILED ||
curlErrorCode == CurlErrorCode.CURLE_GOT_NOTHING ||
curlErrorCode == CurlErrorCode.CURLE_SEND_ERROR ||
curlErrorCode == CurlErrorCode.CURLE_RECV_ERROR)
{
return true;
}
}
}
return false;
}
19
View Source File : WrappedException.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public Exception Unwrap(IDictionary<String, Type> typeMapping)
{
Exception innerException = null;
if (InnerException != null)
{
innerException = InnerException.Unwrap(typeMapping);
UnwrappedInnerException = innerException;
}
Exception exception = null;
// if they have bothered to map type, use that first.
if (!String.IsNullOrEmpty(TypeKey))
{
Type type;
if (typeMapping != null && typeMapping.TryGetValue(TypeKey, out type) ||
baseTranslatedExceptions.TryGetValue(TypeKey, out type))
{
try
{
this.Type = type;
exception = Activator.CreateInstance(this.Type, Message, innerException) as Exception;
}
catch (Exception)
{
// do nothing
}
}
}
if (exception == null)
{
//no standard mapping, fallback to
exception = UnWrap(innerException);
}
if (exception is VssException)
{
((VssException)exception).EventId = this.EventId;
((VssException)exception).ErrorCode = this.ErrorCode;
}
if (exception == null && !String.IsNullOrEmpty(Message))
{
// NOTE: We can get exceptions that we can't create, IE. SqlException, AzureExceptions.
// This is not a failure, we will just wrap the exception in a VssServiceException
// since the type is not available.
exception = new VssServiceException(Message, innerException);
}
if (exception == null && !string.IsNullOrEmpty(TypeName))
{
Debug.replacedert(false, string.Format("Server exception cannot be resolved. Type name: {0}", TypeName));
}
if (exception != null
&& !string.IsNullOrEmpty(HelpLink))
{
exception.HelpLink = HelpLink;
}
if (exception != null
&& !string.IsNullOrEmpty(this.StackTrace))
{
FieldInfo stackTraceField = typeof(Exception).GetTypeInfo().GetDeclaredField("_stackTraceString");
if (stackTraceField != null && !stackTraceField.Attributes.HasFlag(FieldAttributes.Public) && !stackTraceField.Attributes.HasFlag(FieldAttributes.Static))
{
stackTraceField.SetValue(exception, this.StackTrace);
}
}
if (exception != null && exception.GetType() == this.Type)
{
TryUnWrapCustomProperties(exception);
}
return exception;
}
19
View Source File : WrappedException.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private Exception UnWrap(Exception innerException)
{
Exception exception = null;
if (this.Type != null) // m_type is typically null when this.Type getter is hit from here, so the LoadType method will get invoked here.
{
try
{
Object[] args = null;
ConstructorInfo info = GetMatchingConstructor(new[] { typeof(WrappedException) });
if (info != null)
{
// a constructor overload on an exception that takes a WrappedException, is useful
// in cases where the other constructors manipulate the string that we preplaced in,
// which we do not want to happen when unwrapping an exception.
args = new object[] { this };
}
else
{
info = GetMatchingConstructor(new[] { typeof(String), typeof(Exception) });
if (info != null)
{
args = new object[] { Message, innerException };
}
else
{
//try just string
info = GetMatchingConstructor(new[] { typeof(String) });
if (info != null)
{
args = new object[] { Message };
}
else
{
//try default constructor
info = GetMatchingConstructor(new Type[0]);
}
}
}
if (info != null)
{
exception = info.Invoke(args) as Exception;
// only check exceptions that derive from VssExceptions, since we don't have control
// to make code changes to exceptions that we don't own.
Debug.replacedert(!(exception is VssException) || exception.Message == Message,
"The unwrapped exception message does not match the original exception message.",
"Type: {0}{1}Expected: {2}{1}Actual: {3}{1}{1}This can happen if the exception has a contructor that manipulates the input string. You can work around this by creating a constructor that takes in a WrappedException which sets the message verbatim and optionally the inner exception.",
exception.GetType(),
Environment.NewLine,
Message,
exception.Message);
}
}
catch (Exception)
{ }
}
return exception;
}
19
View Source File : AcuminatorLogger.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private string CreateLogMessageFromException(Exception exception, Doreplacedent currentDoreplacedent, LogMode logMode, string reportedFrom)
{
StringBuilder messageBuilder = new StringBuilder(capacity: 256);
if (logMode == LogMode.Error)
{
messageBuilder.AppendLine($"{AreplacedinatorVSPackage.PackageName.ToUpper()} OBSERVED AN UNHANDLED VISUAL STUDIO ERROR|");
}
messageBuilder.AppendLine($"EXCEPTION TYPE: {exception.GetType().Name}")
.AppendLine($"|FILE PATH: {currentDoreplacedent.FilePath}")
.AppendLine($"|MESSAGE: {exception.Message}")
.AppendLine($"|STACK TRACE: {exception.StackTrace}")
.AppendLine($"|TARGET SITE: {exception.TargetSite}")
.AppendLine($"|SOURCE: {exception.Source}")
.AppendLine($"|REPORTED FROM: {reportedFrom}");
return messageBuilder.ToString();
}
19
View Source File : AcuminatorVSPackage.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
private void InitializeLogger()
{
try
{
AreplacedinatorLogger = new AreplacedinatorLogger(this, swallowUnobservedTaskExceptions: false);
}
catch (Exception ex)
{
ActivityLog.TryLogError(PackageName,
$"An error occurred during the logger initialization ({ex.GetType().Name}, message: \"{ex.Message}\")");
}
}
19
View Source File : CopyObjectExtensions.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private static string DumpExceptionMessage(Exception ex)
{
if (ex.InnerException != null)
{
return $"{ex.GetType().Name}({DumpExceptionMessage(ex.InnerException)})";
}
return ex.Message;
}
19
View Source File : ErrorNotifierModule.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected virtual IEnumerable<KeyValuePair<string, string>> GetHeaders(Exception error, HttpContext context, int dropped)
{
yield return CreateHeader("X-ADXSTUDIO-SERVER_NAME", context.Request.ServerVariables["SERVER_NAME"]);
yield return CreateHeader("X-ADXSTUDIO-SCRIPT_NAME", context.Request.ServerVariables["SCRIPT_NAME"]);
yield return CreateHeader("X-ADXSTUDIO-QUERY_STRING", context.Request.ServerVariables["QUERY_STRING"]);
yield return CreateHeader("X-ADXSTUDIO-STATUS_CODE", context.Response.StatusCode.ToString());
yield return CreateHeader("X-ADXSTUDIO-STATUS", context.Response.Status);
yield return CreateHeader("X-ADXSTUDIO-CONTENT-TYPE", context.Response.ContentType);
yield return CreateHeader("X-ADXSTUDIO-CONTENT-ENCODING", context.Response.ContentEncoding.EncodingName);
yield return CreateHeader("X-ADXSTUDIO-EXCEPTION-TYPE", error.GetType().FullName);
yield return CreateHeader("X-ADXSTUDIO-EXCEPTION-DROPPED", dropped.ToString(CultureInfo.InvariantCulture));
}
19
View Source File : ErrorNotifierModule.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected virtual string GetException(Exception error)
{
if (error == null) return null;
const string message =
@"<h3>{0}</h3>
<h5>{1}</h5>
<pre>{2}
{3}{4}
</pre>
";
var sb = new StringBuilder();
var current = error;
while (current != null)
{
var errorMessage = HttpUtility.HtmlEncode(current.Message);
var errorStackTrace = HttpUtility.HtmlEncode(current.StackTrace);
var errorSource = HttpUtility.HtmlEncode(current.Source);
var help = !string.IsNullOrWhiteSpace(current.HelpLink) ? "\r\n" + current.HelpLink : null;
sb.Append(message.FormatWith(errorMessage, current.GetType().FullName, errorStackTrace, errorSource, help));
current = current.InnerException;
}
return sb.ToString();
}
19
View Source File : CmsParentController.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static JObject GetExceptionJson(Exception e)
{
if (e == null)
{
throw new ArgumentNullException("e");
}
var json = new JObject
{
{ "message", new JValue(e.Message) },
{ "type", new JValue(e.GetType().FullName) },
{ "stacktrace", new JValue(e.StackTrace) },
};
if (e.InnerException != null)
{
json["internalexception"] = GetExceptionJson(e.InnerException);
}
return json;
}
19
View Source File : WebEventSource.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string Serialize(Exception error)
{
if (error == null) return null;
var sb = new StringBuilder();
var current = error;
while (current != null)
{
var help = !string.IsNullOrWhiteSpace(current.HelpLink) ? Environment.NewLine + current.HelpLink : null;
sb.Append(current.Message + Environment.NewLine);
sb.Append(current.GetType().FullName + Environment.NewLine);
sb.Append(current.StackTrace + Environment.NewLine + Environment.NewLine);
sb.Append(current.Source);
sb.Append(help + Environment.NewLine + Environment.NewLine);
current = current.InnerException;
}
return sb.ToString();
}
19
View Source File : SimpleAudioRecorderImplementation.cs
License : MIT License
Project Creator : adrianstevens
License : MIT License
Project Creator : adrianstevens
public async Task RecordAsync()
{
if (mediaCapture != null)
{
throw new InvalidOperationException("Recording already in progress");
}
try
{
var captureSettings = new MediaCaptureInitializationSettings()
{
StreamingCaptureMode = StreamingCaptureMode.Audio
};
await InitMediaCapture(captureSettings);
}
catch (Exception ex)
{
CanRecordAudio = false;
DeleteMediaCapture();
if (ex.InnerException != null && ex.InnerException.GetType() == typeof(UnauthorizedAccessException))
{
throw ex.InnerException;
}
throw;
}
var localFolder = ApplicationData.Current.LocalFolder;
var fileName = Path.GetRandomFileName();
var fileOnDisk = await localFolder.CreateFileAsync(fileName);
try
{
await mediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateWav(AudioEncodingQuality.Auto), fileOnDisk);
// await mediaCapture.StartRecordToStorageFileAsync(MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto), fileOnDisk);
}
catch
{
CanRecordAudio = false;
DeleteMediaCapture();
throw;
}
audioFilePath = fileOnDisk.Path;
}
19
View Source File : PaceServer.cs
License : MIT License
Project Creator : afxw
License : MIT License
Project Creator : afxw
private void HandleClientConnection()
{
while (Listening)
{
var client = new PaceClient(listener.AcceptTcpClient());
OnClientConnected(client);
Task.Factory.StartNew(() =>
{
bool isConnected = true;
while (isConnected)
{
try
{
var packet = client.ReadPacket();
OnPacketReceived(client, packet);
}
catch (IOException ex)
{
if (ex.InnerException == null)
{
throw ex;
}
if (ex.InnerException.GetType() == typeof(SocketException))
{
var socketException = (ex.InnerException as SocketException);
if (socketException.ErrorCode == (int)SocketError.ConnectionReset)
{
OnClientDisconnected(client);
isConnected = false;
}
}
}
}
});
}
listener.Stop();
}
19
View Source File : Program.cs
License : MIT License
Project Creator : afxw
License : MIT License
Project Creator : afxw
private void Run()
{
client = new PaceClient();
client.PacketReceived += Client_PacketReceived;
client.PacketSent += Client_PacketSent;
var packetChannel = new PacketChannel();
packetChannel.RegisterHandler<GetSystemInfoRequestPacket>(SystemHandlers.HandleGetSystemInfo);
packetChannel.RegisterHandler<GetDrivesRequestPacket>(SystemHandlers.HandleGetDrives);
packetChannel.RegisterHandler<TakeScreenshotRequestPacket>(SystemHandlers.HandleTakeScreenshot);
packetChannel.RegisterHandler<RestartRequestPacket>(SystemHandlers.HandleRestart);
packetChannel.RegisterHandler<DownloadFileRequestPacket>(FileHandlers.HandleDownloadFile);
packetChannel.RegisterHandler<GetDirectoryRequestPacket>(FileHandlers.HandleGetDirectory);
packetChannel.RegisterHandler<DeleteFileRequestPacket>(FileHandlers.HandleDeleteFile);
packetChannel.RegisterHandler<SendFileRequestPacket>(FileHandlers.HandleSendFile);
TryConnect();
while (isConnected)
{
try
{
var packet = client.ReadPacket();
packetChannel.HandlePacket(client, packet);
}
catch (IOException ex)
{
if (ex.InnerException == null)
{
throw ex;
}
if (ex.InnerException.GetType() == typeof(SocketException))
{
var socketException = (ex.InnerException as SocketException);
if (socketException.ErrorCode == (int)SocketError.ConnectionReset)
{
PrintDebug("Disconnected!");
TryConnect();
}
}
}
}
Console.ReadKey();
}
19
View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public async override Task<IdenreplacedyResult> DeleteAsync(TUser user, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
replacedertNotNull(user, nameof(user));
try
{
await _userStore.DeleteAsync(user.Id, cancellationToken).ConfigureAwait(false);
return IdenreplacedyResult.Success;
}
catch (Exception e)
{
return IdenreplacedyResult.Failed(new IdenreplacedyError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
19
View Source File : RoleStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public async virtual Task<IdenreplacedyResult> CreateAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
replacedertNotNull(role, nameof(role));
try
{
var created = await _roleStore.CreateAsync(role.ToRole(), cancellationToken).ConfigureAwait(false);
role.Id = created.Id;
return IdenreplacedyResult.Success;
}
catch(Exception e)
{
return IdenreplacedyResult.Failed(new IdenreplacedyError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
19
View Source File : RoleStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public async virtual Task<IdenreplacedyResult> UpdateAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
replacedertNotNull(role, nameof(role));
try
{
await _roleStore.UpdateAsync(role.ToRole(), cancellationToken).ConfigureAwait(false);
return IdenreplacedyResult.Success;
}
catch (Exception e)
{
return IdenreplacedyResult.Failed(new IdenreplacedyError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
19
View Source File : RoleStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public async virtual Task<IdenreplacedyResult> DeleteAsync(TRole role, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
replacedertNotNull(role, nameof(role));
try
{
await _roleStore.DeleteAsync(role.Id, cancellationToken).ConfigureAwait(false);
return IdenreplacedyResult.Success;
}
catch (Exception e)
{
return IdenreplacedyResult.Failed(new IdenreplacedyError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
19
View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public async override Task<IdenreplacedyResult> CreateAsync(TUser user, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
replacedertNotNull(user, nameof(user));
try
{
var created = await _userStore.CreateAsync(user.ToUser(), cancellationToken).ConfigureAwait(false);
user.Id = created.Id;
return IdenreplacedyResult.Success;
}
catch (Exception e)
{
return IdenreplacedyResult.Failed(new IdenreplacedyError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
19
View Source File : UserOnlyStore.cs
License : Apache License 2.0
Project Creator : Aguafrommars
License : Apache License 2.0
Project Creator : Aguafrommars
public async override Task<IdenreplacedyResult> UpdateAsync(TUser user, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
ThrowIfDisposed();
replacedertNotNull(user, nameof(user));
try
{
await _userStore.UpdateAsync(user.ToUser(), cancellationToken).ConfigureAwait(false);
return IdenreplacedyResult.Success;
}
catch (Exception e)
{
return IdenreplacedyResult.Failed(new IdenreplacedyError
{
Code = e.GetType().Name,
Description = e.Message
});
}
}
19
View Source File : ExceptionMiddleware.cs
License : MIT License
Project Creator : ahmet-cetinkaya
License : MIT License
Project Creator : ahmet-cetinkaya
private Task HandleExceptionAsync(HttpContext httpContext, Exception e)
{
httpContext.Response.ContentType = "application/json";
httpContext.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
var message = "Internal Server Error";
IEnumerable<ValidationFailure> errors;
if (e.GetType() == typeof(ValidationException))
{
message = e.Message;
errors = ((ValidationException) e).Errors;
httpContext.Response.StatusCode = 400;
return httpContext.Response.WriteAsync(new ValidationErrorDetails
{
StatusCode = 400,
Message = message,
Errors = errors
}.ToString());
}
return httpContext.Response.WriteAsync(new ErrorDetails
{
StatusCode = httpContext.Response.StatusCode,
Message = message
}.ToString());
}
19
View Source File : OverflowCheckSample.cs
License : The Unlicense
Project Creator : ahotko
License : The Unlicense
Project Creator : ahotko
public override void Execute()
{
replacedle("OverflowCheckSampleExecute");
int firstValue;
int secondValue;
int maxValue = 2147483647;
const int maxInt = int.MaxValue;
//do not check for overflow
unchecked
{
firstValue = 2147483647 + 100;
}
Console.WriteLine($"Unchecked sum 1 (in block) (overflow) = {firstValue}");
//...or...
firstValue = unchecked(maxInt + 100);
Console.WriteLine($"Unchecked sum 1 (inline) (overflow) = {firstValue}");
//unchecked by default at compile time and run time because it contains variables
secondValue = maxValue + 100;
Console.WriteLine($"Unchecked sum 2 (variabled added) (overflow) = {secondValue}");
//catch overflow at run time
try
{
checked
{
secondValue = maxValue + 100;
}
Console.WriteLine($"Unchecked sum 2 (in block) (overflow) = {secondValue}");
//...or...
secondValue = unchecked(maxValue + 100);
Console.WriteLine($"Unchecked sum 2 (inline) (overflow) = {secondValue}");
}
catch (Exception e)
{
Console.WriteLine($"Exception '{e.GetType().Name}' with message '{e.Message}' was thrown.");
}
Finish();
}
19
View Source File : ExceptionsSample.cs
License : The Unlicense
Project Creator : ahotko
License : The Unlicense
Project Creator : ahotko
public override void Execute()
{
try
{
throw new MyException("My Exception!");
}
catch (Exception e)
{
Console.WriteLine($"Exception '{e.GetType().Name}' with message '{e.Message}' was thrown.");
}
}
19
View Source File : CommandNotFoundException.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public override string ToString() => $"{this.GetType()}: {this.Message}\nCommand name: {this.CommandName}";
19
View Source File : DuplicateOverloadException.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public override string ToString() => $"{this.GetType()}: {this.Message}\nCommand name: {this.CommandName}\nArgument types: {this.ArgumentSetKey}";
19
View Source File : InvalidOverloadException.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
public override string ToString()
{
// much like System.ArgumentNullException works
return this.Parameter == null
? $"{this.GetType()}: {this.Message}\nMethod: {this.Method} (declared in {this.Method.DeclaringType})"
: $"{this.GetType()}: {this.Message}\nMethod: {this.Method} (declared in {this.Method.DeclaringType})\nArgument: {this.Parameter.ParameterType} {this.Parameter.Name}";
}
19
View Source File : TestHelper.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public static async ValueTask replacedertFailure<T>(this IAsyncEnumerator<T> source, Type exception,
params T[] values)
{
var idx = 0;
try
{
while (await source.MoveNextAsync())
{
replacedert.True(idx < values.Length, "Source has more than the expected " + values.Length + " items");
replacedert.Equal(source.Current, values[idx]);
idx++;
}
replacedert.True(false, "Did not throw any exception but expected: " + exception);
}
catch (TrueException)
{
throw;
}
catch (Exception ex)
{
replacedert.True(values.Length == idx, "Source has less items than expected: " + values.Length + ", actual: " + idx);
replacedert.True(exception.GetTypeInfo().IsreplacedignableFrom(ex.GetType().GetTypeInfo()), "Wrong exception, Expected: " + exception + ", Actual: " + ex);
}
finally
{
await source.DisposeAsync();
}
}
19
View Source File : TestObserver.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public TestObserver<T> replacedertError(Type expectedType, string message = null, bool messageContains = false)
{
var c = Volatile.Read(ref errorCount);
if (c == 0)
{
throw Fail("No error.");
}
var members = expectedType.GetTypeInfo();
var found = 0;
var foundRaw = 0;
for (int i = 0; i < c; i++)
{
if (members.IsreplacedignableFrom(errors[i].GetType().GetTypeInfo()))
{
if (message != null)
{
if (messageContains)
{
if (errors[i].Message.Contains(message))
{
found++;
}
}
else
{
if (errors[i].Message.Equals(message))
{
found++;
}
}
} else {
found++;
}
foundRaw++;
}
}
if (found == 1 && c > 1)
{
throw Fail("Exception present but others as well");
}
if (found > 1)
{
throw Fail("The Exception appears multiple times");
}
if (found == 0)
{
if (foundRaw != 0)
{
throw Fail("Exception type present but not with the specified message" + (messageContains ? " part: " : ": ") + message);
}
throw Fail("Exception not present");
}
return this;
}
19
View Source File : TestObserver.cs
License : Apache License 2.0
Project Creator : akarnokd
License : Apache License 2.0
Project Creator : akarnokd
public TestObserver<T> replacedertCompositeError(int index, Type errorType, string message = null, bool messageContains = false)
{
replacedertError(typeof(AggregateException));
var exs = (errors[0] as AggregateException).InnerExceptions;
if (index < 0 || index >= exs.Count)
{
throw Fail("The AggregateException index out of bounds. Expected: " + index + ", Actual: " + exs.Count);
}
if (errorType.GetTypeInfo().IsreplacedignableFrom(exs[index].GetType().GetTypeInfo()))
{
if (message != null)
{
if (messageContains)
{
if (!exs[index].Message.Contains(message))
{
throw Fail("Error found with a different message part. Expected: " + message + ", Actual: " + exs[index].Message);
}
}
else
{
if (!exs[index].Message.Equals(message))
{
throw Fail("Error found with a different message. Expected: " + message + ", Actual: " + exs[index].Message);
}
}
}
return this;
}
throw Fail("Wrong error type @ " + index + ". Expected: " + errorType + ", Actual: " + exs[index].GetType());
}
See More Examples