gpt4 book ai didi

c# - 在C#异常处理中,有没有一种方法可以检测瞬时错误?

转载 作者:行者123 更新时间:2023-12-03 09:12:11 26 4
gpt4 key购买 nike

我正在使用Azure,但有一个简单的try catch块
我现在正在做的是,当我们遇到任何错误时,我现在将通过电子邮件将错误消息发送给我,我想检测暂时性错误,而忽略为他们发送电子邮件

private void SomeMethod()
{
try
{
// Do stuff
}
catch (Exception ex)
{
HandleError(ex);
return RedirectToAction("Index", "Error");
}
}

protected void HandleError(Exception ex)
{
//and here i want to check if the cause of exception is not a transient error then write a code to email the error details
}

最佳答案

根据您刚刚发布的链接,并提供以下代码示例:

// Define your retry strategy: retry 3 times, 1 second apart.
var retryStrategy = new FixedInterval(3, TimeSpan.FromSeconds(1));

// Define your retry policy using the retry strategy and the Azure storage
// transient fault detection strategy.
var retryPolicy =
new RetryPolicy<StorageTransientErrorDetectionStrategy>(retryStrategy);

// Do some work that may result in a transient fault.
try
{
// Call a method that uses Azure storage and which may
// throw a transient exception.
retryPolicy.ExecuteAction(
() =>
{
this.queue.CreateIfNotExist();
});
}
catch (Exception)
{
// All of the retries failed.
}

根据该文档,在之前,不会引发 异​​常,它不再是重试策略所定义的临时错误。实际上,利用 transient 故障处理应用程序块已经可以完成您在问题中的要求。重试将以静默方式重试(无异常(exception)),直到发生引发异常的时间点-当重试已超出您的重试策略时。

以下内容不应视为“好代码”,它仅仅是TFHAB 如何确定 transient 错误的一个示例。
private void DoStuff()
{
try
{
this.DoSomethingThatCouldPotentiallyCauseTransientErrors(5);
}
catch (Exception ex)
{
// This would not be caught until the "retries" have occurred.
this.HandleException(ex);
return RedirectToAction("Index", "Error");
}
}

private void DoSomethingThatCouldPotentiallyCauseTransientErrors(int retryAttemptsBeforeExceptionThrown)
{
// Note that this will *always throw an exception*,
// I'm (attempting to) simply demonstrate my point of how the transient errors could be defined.

for (int i = 0; i < retryAttemptsBeforeExceptionThrown)
{
try
{
int x = 0;
int y = 0;

int result = x / y;
}
catch (Exception)
{
if (i < retryAttemptsBeforeExceptionThrown-1)
{
// Swallow/ignore the exception, and retry
// Note that anything hitting this block would be considered a "transient error",
// as we are not raising an exception
}
else
{
// Too many failed attempts have occurred, ***now*** we raise an exception to the caller
throw;
}
}
}
}

private void HandleException(Exception ex)
{
// Implementation
}

希望这种回答可以在造成“暂时性错误”的背景下回答约翰的问题

关于c# - 在C#异常处理中,有没有一种方法可以检测瞬时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28460113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com