0

I am trying to check if current exchange exists or not, if it exists I want to deleted and create again. When I do not use try catch and try to delete not existed exchange I lost connection and get an error, how to create an index if does not exist after I try to delete?

export const resetDelayedExchange = (connection ,expectedMessages) => async (message, type) => {

    const exchange = getExchange(type)

    const channel = await connection.createChannel()

    const cleanupDelayedExchange = `${exchange}.${delayedExchange}`

    const restoreOnFailure = e => {
        channel.assertExchange(cleanupDelayedExchange, delayedExchangeType, {durable: true, arguments: {[delayedMessageType]: 'direct'}})

        channel.bindExchange(exchange, cleanupDelayedExchange)

        logger.silly(`publishing message to ${cleanupDelayedExchange}`)

        channel.publish(cleanupDelayedExchange, '', expectedMessages[type].encode(message).finish(), headerArg)
    }

    try {

        channel.deleteExchange(cleanupDelayedExchange, {ifUnused : false})
        connection.on('error', restoreOnFailure)

    } catch (error) {
        restoreOnFailure(error)
    }

}
Palaniichuk Dmytro
  • 2,943
  • 12
  • 36
  • 66

1 Answers1

0

Exchange declarations in RabbitMQ are assertive. This means that you run a statement that declares the existence of the exchange, and if the exchange does not exist, it will be created at that time. If the exchange already exists, then one of two things will happen:

  1. If it was re-declared with different properties, you will get a channel error, which is indicated by a message followed by channel closure. This is how most errors in RabbitMQ are handled. Thus, your client needs to gracefully handle that (in my opinion, the raising of an exception for this would be an inappropriate use of exceptions).

  2. If it is re-declared with the same parameters as previous, then no action will be done; the channel will remain open and usable as-is.

Editorial: I am not aware of too many valid use cases where I'd want to be deleteing and re-declaring exchanges on a regular basis. I consider the exchange to be part of the static configuration of the broker. Changes to exchange configuration are often best done at the time of application deployment.

theMayer
  • 15,456
  • 7
  • 58
  • 90