From d9fdfce4ac85e6f0c42100794b0e51047f5dd0f6 Mon Sep 17 00:00:00 2001 From: Valentin Vakar Date: Thu, 20 Jun 2024 15:45:56 +0100 Subject: [PATCH] Return error instead of killing process --- examples/script.js | 19 ++++++++++++++++++- exec.go | 11 +++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/examples/script.js b/examples/script.js index 674ba6d..6c994d1 100644 --- a/examples/script.js +++ b/examples/script.js @@ -1,8 +1,25 @@ import exec from 'k6/x/exec'; export default function () { + // Basic example: console.log(exec.command("date")); + + // With custom error handling: + try { + var output = exec.command("ls",["-a", "NO_SUCH_DIR"], { + "continue_on_error": true + }); + } catch (e) { + console.log("ERROR: " + e); + if (e.value && e.value.stderr) { + console.log("STDERR: " + String.fromCharCode.apply(null, e.value.stderr)) + } + } + + // without error handling the test will stop when the following command fails console.log(exec.command("ls",["-a","-l"], { "dir": "sub-directory" // optional directory in which the command has to be run })); -} \ No newline at end of file + + console.log("this message will not be printed") +} diff --git a/exec.go b/exec.go index 7e592d1..63b36b3 100644 --- a/exec.go +++ b/exec.go @@ -24,7 +24,8 @@ type EXEC struct { // CommandOptions contains the options that can be passed to command. type CommandOptions struct { - Dir string + Dir string + ContinueOnError bool } // Ensure the interfaces are implemented correctly. @@ -46,14 +47,16 @@ func (exec *EXEC) Exports() modules.Exports { } // Command is a wrapper for Go exec.Command -func (*EXEC) Command(name string, args []string, option CommandOptions) string { +func (*EXEC) Command(name string, args []string, option CommandOptions) (string, error) { cmd := exec.Command(name, args...) if option.Dir != "" { cmd.Dir = option.Dir } + out, err := cmd.Output() - if err != nil { + if err != nil && !option.ContinueOnError { log.Fatal(err.Error() + " on command: " + name + " " + strings.Join(args, " ")) } - return string(out) + + return string(out), err }