node.jsnestjscircuit-breaker

Opening circuit breaker based on the response status with NodeJs (Opossum)


I am using opossum to implement circuit breaker for my nodeJs application. Currently whenever there is an error, either it's Bad Request or Bad Gateway, the circuit breaker is opened and blocked the next calls.

Is there a way to implement to open circuit breaker only for some response status like HttpStatus.INTERNAL_SERVER_ERROR and so on.

The following is my current code.

       const response = this.circuitBreakers
            .fire(...args)
            .catch((result) => {
                console.log(`in circuit : ${result}`);
                this.logger.error(result?.response);
            });

Right now, the only way I found is to close the circuit breaker immediately after it's open if it's returning other statuses like following

const response = this.circuitBreakers
                .fire(...args)
                .catch((result) => {
                    if (parseInt(result.response.status != 500) {
                        this.circuitBreaker.close();
                    } else {
                        console.log(`in circuit : ${result}`);
                        this.logger.error(result?.response);
                    }
                });
            

Solution

Thanks to Charchit Kapoor's answer, here is the solution I added in my Circuit Breaker 's option

const options: CircuitOptions = {
  errorFilter: (err) => {
    const status = parseInt(err.response.status, 10);
    // I want the circuit breaker to open only when the error status is 500
    if (status != 500) {
      return false;
    }
    return true;
  },
}

Hope this helps.


Solution

  • I think you are looking for the errorFilter config function, which is a part of the options object, passed in the constructor for CircuitBreaker.

    Link to documentation of errorFilter.