gpt4 book ai didi

c# - 在 OnMessageOptions 中使用 ExceptionReceived

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:03 25 4
gpt4 key购买 nike

我正在尝试使用方法 QueueClient.OnMessage(Action<BrokeredMessage>, OnMessageOptions) 。在 OnMessageOptions我编写了这个简单的ExceptionReceived事件:

void LogErrors(object sender, ExceptionReceivedEventArgs e)
{
if (e.Exception != null)
{
Trace.TraceError("Exception captured: " + e.Exception.Message);
}
}

我的疑问是如何获取“LogErrors”BrokeredMessage这是在回调中进行处理的,以便在发生 BrokeredMessage 时保存包含错误的日志。

最佳答案

我试图了解如何从 ExceptionReceived 回调中/在 ExceptionReceived 回调中获取消息,但参数中不存在该信息。这是我的示例代码:

var connectionString = "my-connection-string";
var queueName = "my-queue-name";
var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

var options = new OnMessageOptions();
options.ExceptionReceived += (sender, args) =>
{
// Neither sender or args contains information about the message being processed
};

client.OnMessage(brokeredMessage =>
{
throw new Exception();
}, options);

根据您的需要,简单的解决方案是将回调包装在 try/catch 中:

client.OnMessage(brokeredMessage =>
{
try
{
// Process the message
...

// Complete the message (depends on the )
brokeredMessage.Complete();
}
catch (Exception ex)
{

Trace.TraceError("Exception captured: " + ex.Message);

// Here you have access to the brokeredMessage so you can log what you want.
...
//Abandon the message so that it could be re-process ??
brokeredMessage.Abandon();
}

}, options);

您可以将此包装器放入函数中或为 QueueClient 创建扩展方法后:

public static class QueueClientExtensions
{
public static void OnCustomMessage(this QueueClient queueClient, Action<BrokeredMessage> callback,
OnMessageOptions onMessageOptions)
{
queueClient.OnMessage(message =>
{
try
{
// process the message
callback(message);

//complete if success
message.Complete();
}
catch (Exception ex)
{
// Here you have access to the brokeredMessage so you can log what you want.
// message.GetBody<string>()
Trace.TraceError("Exception captured: " + ex.Message);

//Abandon the message so that it could be re-process
message.Abandon();
}

}, onMessageOptions);
}
}

并以同样的方式调用该方法:

var queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
queueClient.OnCustomMessage(brokeredMessage =>
{
// Process the message
...
}, new OnMessageOptions());

关于c# - 在 OnMessageOptions 中使用 ExceptionReceived,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37962694/

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