How do I fail a script running in Bitbucket Pipelines?

8.8k views Asked by At

When a pipeline runs a node series of commands, how can I trigger a fail within the pipeline?

I have tried the following:

const failBuild = function(message) {
  console.error('Deploy failed: ', message)
  throw new Error('Deploy failed')
}

I see the "Deploy failed" message, but the pipeline still says "Success".

3

There are 3 answers

1
BlueM On BEST ANSWER

Bb Pipelines fail when a command exits with a non-zero exit code. So, if you want the pipeline to fail, you have to make sure the code is not 0.

In your case (note for people reading this later: see comments), you get 0 as exit status, because the throw is executed in a promise, but then catched in the promise’s catch() function – which does neither stop execution nor have any influence on the exit code.

Solution: explicitly throw an error in the catch() function.

0
Maxime Rossini On

The accepted answer states:

Solution: explicitly throw an error in the catch() function.

So if I understand that correctly, it suggests you should write the script as:

async function main() { throw "err"; }
main().catch(e => { throw e; });

However, this does not work: the exit code is still 0, and the console displays a nasty warning:

> node "main.js"
(node:32996) UnhandledPromiseRejectionWarning: err
(node:32996) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:32996) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
> $?
0

The correct way to bubble up the error to the node process is:

process.on('unhandledRejection', up => { throw up });
async function main() { throw "err"; }
main();

This way, you get teh following result:

> node "main.js"
test2.js:1
process.on('unhandledRejection', up => { throw up });
                                         ^
err
> $?
1

Which is a little bit better (except the stacktrace is not very clear).

1
Matt Royal On

For anyone else who might be struggling with this...

You need to return a non zero as already mentioned, I find the easiest way to do this is by passing a negative integer to PHP's exit() function.

https://php.net/manual/en/function.exit.php

if($condition == true)
{
    // Whatever we were doing, it worked YAY!!
    exit();
}
else
{
    // Something went wrong so fail the step in the pipeline
    exit(-1);
}