我正在尝试使用方法 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());
我是一名优秀的程序员,十分优秀!