NodeJS @azure/service-bus: Any example to send message to deadletter manually?

801 views Asked by At

I could not find any examples to send message to deadletter queue manually.

let { ServiceBusClient, ReceiveMode } = require('@azure/service-bus'),
    serviceBusClient = ServiceBusClient.createFromConnectionString(SERVICE_BUS_SECRET),
    queueClient = serviceBusClient.createQueueClient(QUEUE),
    receiver = queueClient.createReceiver(ReceiveMode.peekLock);

const onMessageHandler = async (brokeredMessage) => {
    await brokeredMessage.deadletter({
        deadletterReason: 'testingReason', 
        deadLetterErrorDescription: 'testingDesc'
    });
};

const onErrorHandler = (error) => {
    console.log(error);
};

receiver.registerMessageHandler(onMessageHandler, onErrorHandler);

When I run above code, there is error like deadletter() is not defined.

1

There are 1 answers

0
Jim Xu On BEST ANSWER

Regarding the issue, please refer to the following code

async function main() {
  const sbClient = ServiceBusClient.createFromConnectionString(
    connectionString
  );
  const queueClient = sbClient.createQueueClient(queueName);

  try {
    const receiver = queueClient.createReceiver(ReceiveMode.peekLock);
    const receiverPromise = new Promise((resolve, _reject) => {
      const onMessageHandler = async (brokeredMessage) => {
        console.log("Received message: ", brokeredMessage.messageId);
        await brokeredMessage.deadLetter({
          deadletterReason: "test",
          deadLetterErrorDescription: "test",
        });

        console.log(
          `send message  ${brokeredMessage.messageId} to dead letter queue successfully `
        );
      };

      const onErrorHandler = (err) => {
        if (err.retryable === true) {
          console.log(
            "Receiver will be recreated. A recoverable error occurred:",
            err
          );
          resolve();
        } else {
          console.log("Error occurred: ", err);
        }
      };

      receiver.registerMessageHandler(onMessageHandler, onErrorHandler, {
        autoComplete: false,
      });
    });

    await receiverPromise;
    await receiver.close();
    
  } finally {
    await queueClient.close();
    await sbClient.close();
  }
}

main().catch((err) => {
  console.log("Error occurred: ", err);
});

enter image description here