Skip to content

Commit

Permalink
Merge pull request #24 from vvakar/returnError
Browse files Browse the repository at this point in the history
Return error instead of killing process
  • Loading branch information
pablochacin authored Jul 16, 2024
2 parents 0215411 + d9fdfce commit 3201b2f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
19 changes: 18 additions & 1 deletion examples/script.js
Original file line number Diff line number Diff line change
@@ -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
}));
}

console.log("this message will not be printed")
}
11 changes: 7 additions & 4 deletions exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}

0 comments on commit 3201b2f

Please sign in to comment.