我考虑使用Polly https://github.com/App-vNext/Polly#handing-return-values-and-policytresult创建策略来记录异常并重新抛出。
我没有找到允许它开箱即用的现有方法,但我看到的一些选项是
Fallback
// Specify a substitute value or func, calling an action (e.g. for logging)
// if the fallback is invoked.
Policy.Handle<Whatever>()
.Fallback<UserAvatar>(UserAvatar.Blank,
onFallback: (exception, context) =>
{
_logger.Log(exception, context);
throw exception;
});
问题:可以从 Fallback 中抛出异常吗?
Timeout
Policy.Timeout(1, T30meoutStrategy.Pessimistic,
(context, timespan, task) =>
{
// ContinueWith important!: the abandoned task may very well still be executing,
// when the caller times out on waiting for it!
task.ContinueWith(t =>
{
if (t.IsFaulted)
{
logger.Error(context,t.Exception);
throw exception;
}
});
}
Or Retry
Policy.Handle<DivideByZeroException>().Retry(0,
(exception, retryCount) =>
{
logger.Error(context,exception);
throw exception;
});
问:是否支持0次重试?
或者亲吻并写下简单的尝试/捕获自己扔。
这些方法中哪种更好?
您有什么建议?