Skip to content

Add Get-FormattedError function#901

Open
praneeth-0000 wants to merge 1 commit intomainfrom
Get-FormattedError
Open

Add Get-FormattedError function#901
praneeth-0000 wants to merge 1 commit intomainfrom
Get-FormattedError

Conversation

@praneeth-0000
Copy link
Collaborator

@praneeth-0000 praneeth-0000 commented Feb 16, 2026

Added Get-FormattedError function which formats error object from catch block and formats it so it's user friendly and readable.

Network Spec Example

  • Without using the Get-FormattedError function
image
  • With using the Get-FormattedError function
image
  • With using the Get-FormattedError function -IncludeDetails
image

Data Spec Example

  • Without using the Get-FormattedError function
image
  • With using the Get-FormattedError function
image

@praneeth-0000 praneeth-0000 self-assigned this Feb 16, 2026
@merill
Copy link
Collaborator

merill commented Feb 16, 2026

This looks really good @praneeth-0000

Nice work

Copy link
Collaborator

@merill merill left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@alexandair can you review the code before I merge?

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds a new private PowerShell helper, Get-FormattedError, to turn catch error records into a more readable, user-friendly bullet list (with optional extra details).

Changes:

  • Introduces Get-FormattedError to format ErrorRecord into a concise markdown-ish message.
  • Attempts to extract HTTP status, Graph-style JSON error messages, and request IDs.
  • Adds an -IncludeDetails switch to include category and exception type.
Comments suppressed due to low confidence (2)

src/powershell/private/core/Get-FormattedError.ps1:68

  • ConvertFrom-Json error behavior can vary by host/version; to guarantee your inner try/catch reliably catches parsing failures, pass -ErrorAction Stop (or call it in a way that ensures a terminating error) so you don’t end up silently continuing with partially populated variables.
                    $errorJson = $jsonContent | ConvertFrom-Json

src/powershell/private/core/Get-FormattedError.ps1:116

  • Joining with "`n" can produce inconsistent output across environments (e.g., Windows tools expecting CRLF). If this output is intended for logs/test artifacts consumed on multiple platforms, consider using [Environment]::NewLine to normalize line endings.
            $formattedError = ($errorDetails | ForEach-Object { "- $_" }) -join "`n"

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +45 to +46
if ($ErrorObject.Exception.Response.StatusCode) {
$httpStatus = "$($ErrorObject.Exception.Response.StatusCode.value__) $($ErrorObject.Exception.Response.StatusCode)"
Copy link

Copilot AI Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exception.Response is not a property on many exception types; accessing a missing property can throw PropertyNotFoundException and force the function into the outer catch (losing the intended formatting). Consider checking for the property/type more defensively (e.g., inspect PSObject.Properties['Response'], or gate this behind known HTTP/Web exception types), and avoid using .value__ (it’s an internal enum field) by casting to [int] instead.

Suggested change
if ($ErrorObject.Exception.Response.StatusCode) {
$httpStatus = "$($ErrorObject.Exception.Response.StatusCode.value__) $($ErrorObject.Exception.Response.StatusCode)"
if ($ErrorObject.Exception -and
$ErrorObject.Exception.PSObject.Properties['Response'] -and
$ErrorObject.Exception.Response -and
$ErrorObject.Exception.Response.PSObject.Properties['StatusCode']) {
$statusCode = $ErrorObject.Exception.Response.StatusCode
$httpStatus = ("{0} {1}" -f ([int]$statusCode), $statusCode)

Copilot uses AI. Check for mistakes.
Comment on lines +56 to +69
# Find the actual error JSON by looking for {"error" pattern
$jsonContent = $null
$startIndex = $ErrorObject.ErrorDetails.Message.IndexOf('{"error"')
if ($startIndex -ge 0) {
# Find the matching closing brace for this JSON object
$lastIndex = $ErrorObject.ErrorDetails.Message.LastIndexOf('}')
if ($lastIndex -gt $startIndex) {
$jsonContent = $ErrorObject.ErrorDetails.Message.Substring($startIndex, $lastIndex - $startIndex + 1)
}
}

if ($jsonContent) {
$errorJson = $jsonContent | ConvertFrom-Json

Copy link

Copilot AI Mar 2, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The JSON extraction logic is brittle: IndexOf('{"error"') won’t match valid bodies with leading whitespace/newlines, different casing, or other JSON shapes, and LastIndexOf('}') can over-capture if the message contains additional braces after the JSON body. A more robust approach is to locate the first { of the JSON payload and then either (1) regex-capture the JSON block, or (2) attempt ConvertFrom-Json on progressively smaller suffixes until it parses, falling back cleanly when it doesn’t.

Suggested change
# Find the actual error JSON by looking for {"error" pattern
$jsonContent = $null
$startIndex = $ErrorObject.ErrorDetails.Message.IndexOf('{"error"')
if ($startIndex -ge 0) {
# Find the matching closing brace for this JSON object
$lastIndex = $ErrorObject.ErrorDetails.Message.LastIndexOf('}')
if ($lastIndex -gt $startIndex) {
$jsonContent = $ErrorObject.ErrorDetails.Message.Substring($startIndex, $lastIndex - $startIndex + 1)
}
}
if ($jsonContent) {
$errorJson = $jsonContent | ConvertFrom-Json
# Find the actual error JSON by locating the first JSON object and parsing it
$errorJson = $null
$rawMessage = $ErrorObject.ErrorDetails.Message
$startIndex = $rawMessage.IndexOf('{')
if ($startIndex -ge 0) {
# First try to parse from the first '{' to the end
$jsonCandidate = $rawMessage.Substring($startIndex)
try {
$errorJson = $jsonCandidate | ConvertFrom-Json
}
catch {
# If that fails, progressively trim from the end until parsing succeeds
for ($end = $rawMessage.Length; $end -gt $startIndex; $end--) {
$length = $end - $startIndex
$slice = $rawMessage.Substring($startIndex, $length)
try {
$errorJson = $slice | ConvertFrom-Json
break
}
catch {
# Ignore and continue trimming
}
}
}
}
if ($errorJson) {

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants