首页 > 解决方案 > 在 Node.js 中使用 Bull 有条件地重试失败的作业

问题描述

我知道我们可以使用下面的backoff属性在Bull 中重试失败的作业Bull

var Queue = require('bull');
var myQueue = new Queue('myQueue');

runQueryQueue
    .add(data, {
      jobId: uid,
      attempts: 10,
      backoff: {
        type: 'exponential', 
        delay: 2000, 
      },
      stackTraceLimit: 100,
    })
    .then((result) => {})
    .catch(console.log);

但我只想在失败原因值得重试时重试 - 例如超时、速率限制等,而不是在错误与用户输入等相关时重试。

如何检查失败错误消息并决定重试?

标签: node.jsqueuejobs

解决方案


您可以将作业标记为完成,例如不抛出错误,而是将错误数据写入作业完成的结果。如果有任何错误迹象,可以以不同的方式处理结果。

async function jobProcess(job) {
  if (doNotRetryError) {
    return doNotRetryError
  } else if (anyOtherError) {
    throw new Error('retry')
  } else {
    return {success: true}
  }
}

async function jobCompleted(job, result) {
  if (result instanceof Error) {
    // some error happened, but job shouldn't be retried
  } else {
    // job completed
  }
}

推荐阅读