Skip to content

Failing without throwing from within job #68

@God-damnit-all

Description

@God-damnit-all

I am wanting to abort a ThreadJob early if $LASTEXITCODE doesn't equal 0. Throwing accomplishes that, but I'm wanting the return value to only be the stderr output of the native application.

Here's what I would like if exit 1 hypothetically set the job's State property to "Failed":

$jobObject = Start-ThreadJob {
    curl --silent --show-error this_will_cause_an_error
    if ($LASTEXITCODE) {
        exit 1
    }
}
$null = Wait-Job $jobObject
$jobData = Receive-Job $jobObject 2>&1
if ($jobObject.State -eq 'Failed') {
    throw $jobData
}

And here is my current, ugly workaround:

$jobObject = Start-ThreadJob {
    $err = $(
        $out = curl --silent --show-error this_will_cause_an_error
    ) 2>&1
    if ($LASTEXITCODE) {
        throw $err
    } else {
        Write-Output $out
    }
}
$null = Wait-Job $jobObject
$jobData = Receive-Job $jobObject 2>&1
if ($jobObject.State -eq 'Failed') {
    throw $jobData
}

My problem with this is that the redirection wrapping you have to resort to is very kludgy, with $err being the outermost variable being set and the proper output set within a subexpression. I'm hoping for an alternative.

As mentioned before, exit 1 would be great, though I'm not sure how you'd feel about that producing a different State result from it being used in a BackgroundJob, since it doesn't work there either.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions