Powershell: Suggestion: implement new operator for error handing

Created on 12 Jan 2020  路  3Comments  路  Source: PowerShell/PowerShell

powershell language enables you to think about problems from a different perspective. You learn to solve problems in a different way.

example:

$var! = exp

the operator "!" (or maybe we choose another) If the return value is not error or exitcode 0 then assign to variable $var the "exp" if is error then not assign ad terminate error

PS> type script.ps1

$content!= cat fileNotexist
$content -replace '\s'

this code is just syntactic sugar for

try {
  $erroractionpreference= 'stop'
  $content= cat fileNotexist
} catch{break}
$content -replace '\s'

making for some code it easier to write and less typing

this operator can be used with variable or expression (some code)! or maybe in scriptblock
is not supposed to replace try/catch but is another way to think about error handling....this operator is insprired to Rust and is cool to implement in PS.

Issue-Enhancement WG-Language

Most helpful comment

You just want it to exit early if there's an error? What about:

$content = Get-Content doesnotexist || $(return)
$content -replace '\s'

All 3 comments

Interesting idea, but we'd need to properly define how this would really work for PS. You can already do things like $var = try { get-content -erroraction stop -path $nonexistentFile } catch { "fallback value" } so this would essentially be some kind of shortcut for this syntax, though I'm not clear on what that fallback would be here?

It's also not clear how this would behave with subexpressions or pipelines -- would this simply swallow any errors that occur for the duration of the entire expression?

Finally, I don't think ! is a great choice for the operator; it reminds far too much of the != operator for C# in your example syntax, which is -ne in PS.

You just want it to exit early if there's an error? What about:

$content = Get-Content doesnotexist || $(return)
$content -replace '\s'

You just want it to exit early if there's an error? What about:

$content = Get-Content doesnotexist || $(return)
$content -replace '\s'

yes its awsome but in rust it can be chained for example with '!' operator ( in rust is ? operator)

prototype

$c=[io.file]::OpenText('c:\file.txt)!..Readline()!

if OpenText return error stop otherwise continue to Readline() if readline return error stop otherwise store output to $c

$c!=[io.file]::OpenText('c:\file.txt)..Readline()

or maybe
$c=([io.file]::OpenText('c:\file.txt)..Readline())!

if this expression return error stop

Was this page helpful?
0 / 5 - 0 ratings