ProblemDetails Fallback

Return RFC 7807 ProblemDetails for unhandled exceptions, ideal for API clients.

Full source

File: pwsh/tutorial/examples/18.4-ExceptionHandling-ProblemDetails.ps1

#
# Sample: Exception Handling with ProblemDetails Fallback
# Demonstrates JSON responses using Problem Details (RFC 7807) without custom handlers.
# FileName: 18.4-ExceptionHandling-ProblemDetails.ps1
#
param(
    [int]$Port = 5000,
    [IPAddress]$IPAddress = [IPAddress]::Loopback
)

Initialize-KrRoot -Path $PSScriptRoot
New-KrLogger | Set-KrLoggerLevel -Level Debug |
    Add-KrSinkConsole | Register-KrLogger -Name 'console' -SetAsDefault

New-KrServer -Name 'Exception Handling - ProblemDetails'
Add-KrEndpoint -Port $Port -IPAddress $IPAddress

# No custom handler or re-exec path; rely on built-in JSON/ProblemDetails
Enable-KrExceptionHandling -IncludeDetailsInDevelopment -UseProblemDetails

Enable-KrConfiguration

# A normal route
Add-KrMapRoute -Verbs Get -Pattern '/hello' -ScriptBlock {
    Write-KrJsonResponse @{ msg = 'Hello from /hello' } -StatusCode 200
}

Add-KrMapRoute -Verbs Get -Pattern '/boom' -ScriptBlock {
    throw 'This will be formatted as ProblemDetails (500)'
}

Write-Host "Server starting on http://$($IPAddress):$Port" -ForegroundColor Green
Write-Host 'Try these URLs:' -ForegroundColor Yellow
Write-Host "  http://$($IPAddress):$Port/hello   - Happy path" -ForegroundColor Cyan
Write-Host "  http://$($IPAddress):$Port/boom  - Triggers ProblemDetails JSON" -ForegroundColor Cyan
Write-Host ''

Start-KrServer

Step-by-step

  1. Logger: Register console logger.
  2. Server: Create and listen on 127.0.0.1:5000.
  3. Middleware: Enable-KrExceptionHandling -UseProblemDetails to emit standardized JSON.
  4. Route: Map /oops that throws to exercise the handler.
  5. Response: 500 status with ProblemDetails fields like type, title, status, and traceId.
  6. Start: Apply configuration and start.

Try it

curl -i http://127.0.0.1:5000/oops

PowerShell:

$r = Invoke-WebRequest -Uri http://127.0.0.1:5000/oops -UseBasicParsing -SkipHttpErrorCheck
try { $json = $r.Content | ConvertFrom-Json -AsHashtable } catch { $json = $null }
$r.StatusCode
$json

Troubleshooting

  • Client can’t parse JSON? Some clients receive gzipped content; ensure decompression or disable gzip for debugging.
  • Getting generic 500 text? Confirm -UseProblemDetails is enabled and nothing overwrote the response later in the pipeline.

References


Previous / Next

Previous: C# Inline Handler Next: Developer Exception Page