Alternatively you can call error(String message) step to stop the pipeline and set its status to FAILED . For example, if your stage 1 calls error(msg) step like: stage("Stage 1") { steps { script { error "This pipeline stops here!" } } }
The following are some of the best practices you can follow while using parameters in a Jenkinsfile. Never pass passwords in the String or Multi-line parameter block. Instead, use the password parameter of access Jenkins credentials with credential id as the parameter. Try to use parameters only if required.
The script has the elements “pipeline”, “agent” and “steps” which are specific to Declarative Pipeline syntax; “stage” is common to both Declarative and Scripted; and finally, node” is specific for the Scripted one. “Pipeline” defines the block that will contain all the script content.
The exception that you are seeing is due to script security and sandboxing. Basically, by default, when you run a pipeline script, it runs in a sandbox which only allow usage of certain methods and classes. There are ways to whitelist operations, check the link above.
The @NonCPS
annotation is useful when you have methods which use objects which aren't serializable. Normally, all objects that you create in your pipeline script must be serializable (the reason for this is that Jenkins must be able to serialize the state of the script so that it can be paused and stored on disk).
When you put @NonCPS
on a method, Jenkins will execute the entire method in one go without the ability to pause. Also, you're not allowed to reference any pipeline steps or CPS transformed methods from within an @NonCPS
annotated method. More information about this can be found here.
As for the exception handling: Not 100% sure what you are experiencing; I've tried the following and it works as expected:
@NonCPS
def myFunction() {
throw new RuntimeException();
}
try {
myFunction();
} catch (Exception e) {
echo "Caught";
}
and
@NonCPS
def myFunction() {
throw new RuntimeException();
}
def mySecondFunction() {
try {
myFunction();
} catch (Exception e) {
echo "Caught";
}
}
mySecondFunction();
and finally:
@NonCPS
def myFunction() {
throw new RuntimeException();
}
@NonCPS
def mySecondFunction() {
try {
myFunction();
} catch (Exception e) {
echo "Caught";
}
}
mySecondFunction();
All print "Caught" as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With