Closed Yendred closed 3 years ago
Hey there @Yendred. I agree with the removal of the try/catch and will look to implement. For now, could you use $ErrorActionPreference = 'Stop'
to create the same behavior?
Out of curiosity, what is causing the exceptions when running this function?
@gdbarron I did not try $ErrorActionPreference = 'Stop'
as I have since rewritten the code to make sure I always receive a valid record when calling Get-ServiceNowTableEntry
. The table has less than 2000 records and I only need 3 attributes I decided to get all of them at once.
In short the SNOW REST API was raising a 404 exception (Not Found). This was being written to the screen but ultimate did not affect the flow of the code. Visually unpleasing, but non detrimental.
But I thought I would try your suggestion and it will work. I have to set $ErrorActionPreference
before and after the call. The catch
will never be called unless you uncomment the $ErrorActionPreference
in the try
. You should reset it back in the finally
, but this has no direct affect on this test
# code to setup the URL and Credentials or purposefully omitted
$tableName = 'sys_user'
$sys_id = '<sys_id of a valid user>' # known user
$sys_id = '0' # invalid user
$results = $null
try {
#$ErrorActionPreference = 'Stop'
$results = Get-ServiceNowTableEntry -Table $tableName -MatchExact @{sys_id = $sys_id}
} catch {
Write-Host 'Log Exception'
} finally {
#$ErrorActionPreference = 'Continue'
}
if ($null -eq $results) {
Write-Host 'Did not find a record'
}
Write-Host 'Continue with application'
We routinely call 'Get-ServiceNowTableEntry' to call a custom table to determine if a record exists, so we can choose to either create or update the record. If the record does not exist 'Get-ServiceNowTableEntry' writes out the exception ($PSItem) to the console. I would prefer that the exception is simply propagated. Propagating the exception will allow me to choose what to do. Since this is an automated process, this exception would be valuable to add to our exception logs so that is is tracked and ultimately corrected.
Currently I get a ugly console experience and $null return.
This is what exists today
Try {...} Catch { Write-Error $PSItem } }
Would like to see Try/Catch removed or change to the equivalent to this
Try {...} Catch { throw } }