-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
movingMessagesToDLQ.ts
80 lines (68 loc) · 2.58 KB
/
movingMessagesToDLQ.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
/**
* This sample demonstrates scenarios as to how a Service Bus message can be explicitly moved to
* the DLQ. For other implicit ways when Service Bus messages get moved to DLQ, refer to -
* https://docs.microsoft.com/azure/service-bus-messaging/service-bus-dead-letter-queues
*
* Run processMessagesInDLQ example after this to see how the messages in DLQ can be reprocessed.
*
* @summary Demonstrates scenarios as to how a Service Bus message can be explicitly moved to
* the DLQ
*/
import { ServiceBusClient, ServiceBusMessage } from "@azure/service-bus";
import { DefaultAzureCredential } from "@azure/identity";
// Load the .env file if it exists
import * as dotenv from "dotenv";
dotenv.config();
// Define connection string and related Service Bus entity names here
const fqdn = process.env.SERVICEBUS_FQDN || "<your-servicebus-namespace>.servicebus.windows.net";
const queueName = process.env.QUEUE_NAME || "<queue name>";
const credential = new DefaultAzureCredential();
const sbClient: ServiceBusClient = new ServiceBusClient(fqdn, credential);
export async function main() {
try {
// Sending a message to ensure that there is atleast one message in the main queue
await sendMessage();
await receiveMessage();
} finally {
await sbClient.close();
}
}
async function sendMessage() {
// createSender() can also be used to create a sender for a topic.
const sender = sbClient.createSender(queueName);
const message: ServiceBusMessage = {
body: {
name: "Creamy Chicken Pasta",
type: "Dinner",
},
contentType: "application/json",
subject: "Recipe",
};
await sender.sendMessages(message);
await sender.close();
}
async function receiveMessage() {
// If receiving from a subscription you can use the createReceiver(topicName, subscriptionName) overload
const receiver = sbClient.createReceiver(queueName);
const messages = await receiver.receiveMessages(1);
if (messages.length) {
console.log(
">>>>> Deadletter the one message received from the main queue - ",
messages[0].body,
);
// Deadletter the message received
await receiver.deadLetterMessage(messages[0], {
deadLetterReason: "Incorrect Recipe type",
deadLetterErrorDescription: "Recipe type does not match preferences.",
});
} else {
console.log(">>>> Error: No messages were received from the main queue.");
}
await receiver.close();
}
main().catch((err) => {
console.log("Moving Messages To DLQ Sample - Error occurred: ", err);
process.exit(1);
});