< Summary - Kestrun — Combined Coverage

Information
Class: Public.Middleware.Enable-KrExceptionHandling
Assembly: Kestrun.PowerShell.Public
File(s): /home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Middleware/Enable-KrExceptionHandling.ps1
Tag: Kestrun/Kestrun@2d87023b37eb91155071c91dd3d6a2eeb3004705
Line coverage
0%
Covered lines: 0
Uncovered lines: 50
Coverable lines: 50
Total lines: 238
Line coverage: 0%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100 10/13/2025 - 16:52:37 Line coverage: 0% (0/50) Total lines: 238 Tag: Kestrun/Kestrun@10d476bee71c71ad215bb8ab59f219887b5b4a5e

Metrics

File(s)

/home/runner/work/Kestrun/Kestrun/src/PowerShell/Kestrun/Public/Middleware/Enable-KrExceptionHandling.ps1

#LineLine coverage
 1<#
 2.SYNOPSIS
 3    Enables exception handling middleware for a Kestrun server instance.
 4.DESCRIPTION
 5    This cmdlet configures the exception handling middleware for a Kestrun server instance,
 6    allowing for customizable error handling and response generation.
 7.PARAMETER Server
 8    The Kestrun server instance (resolved if omitted via Resolve-KestrunServer).
 9.PARAMETER ExceptionHandlingPath
 10    The path to re-execute when an exception occurs (e.g., '/error').
 11.PARAMETER CreateScopeForErrors
 12    If specified, creates a new scope for handling errors.
 13.PARAMETER AllowStatusCode404Response
 14    If specified, allows handling of 404 status code responses.
 15.PARAMETER IncludeDetailsInDevelopment
 16    If specified, includes detailed error information when the environment is set to Development.
 17.PARAMETER UseProblemDetails
 18    If specified, formats error responses using the Problem Details standard (RFC 7807).
 19.PARAMETER Compress
 20    If specified, compress the json response for error handling.
 21.PARAMETER DeveloperExceptionPage
 22    If specified, enables the Developer Exception Page middleware with default options.
 23.PARAMETER SourceCodeLineCount
 24    The number of source code lines to display around the error line in the Developer Exception Page.
 25.PARAMETER SourceCodePath
 26    The base path to use for locating source code files in the Developer Exception Page.
 27.PARAMETER LanguageOptions
 28    A LanguageOptions object defining the scripting language, code, references, imports, and arguments
 29    for custom error handling logic.
 30.PARAMETER ScriptBlock
 31    A PowerShell script block to execute for custom error handling logic.
 32.PARAMETER Code
 33    A string containing the code to execute for custom error handling logic.
 34.PARAMETER Language
 35    The scripting language of the provided code (e.g., PowerShell, CSharp, VisualBasic).
 36.PARAMETER CodeFilePath
 37    The file path to a script file containing the code to execute for custom error handling logic.
 38.PARAMETER ExtraRefs
 39    An array of additional assemblies to reference when executing the custom error handling code.
 40.PARAMETER Arguments
 41    A hashtable of arguments to pass to the custom error handling code.
 42.PARAMETER ExtraImports
 43    An array of additional namespaces to import when executing the custom error handling code.
 44.PARAMETER PassThru
 45    If specified, returns the modified Kestrun server instance.
 46.OUTPUTS
 47    The modified Kestrun server instance if the PassThru parameter is specified; otherwise, no output.
 48.EXAMPLE
 49    Enable-KrExceptionHandling -ExceptionHandlingPath '/error' -CreateScopeForErrors -AllowStatusCode404Response -PassTh
 50    Enables exception handling middleware on the default Kestrun server instance,
 51    re-executing requests to '/error' when exceptions occur, creating a scope for error handling,
 52    and allowing handling of 404 status code responses. The modified server instance is returned.
 53.EXAMPLE
 54    Enable-KrExceptionHandling -Server $myServer -DeveloperExceptionPage -SourceCodeLineCount 10 -SourceCodePath 'C:\MyA
 55    Enables the Developer Exception Page middleware on the specified Kestrun server instance,
 56    displaying 10 lines of source code around the error line and using 'C:\MyApp' as the base path for source files.
 57.EXAMPLE
 58    $langOptions = [Kestrun.Hosting.Options.LanguageOptions]::new()
 59    $langOptions.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 60    $langOptions.Code = { param($exception) "An error occurred: $($exception.Message)" }
 61    Enable-KrExceptionHandling -Server $myServer -LanguageOptions $langOptions
 62    Enables custom exception handling on the specified Kestrun server instance,
 63    executing the provided PowerShell code block when an exception occurs. The code block receives the exception object 
 64    The custom error handling logic can be defined using the LanguageOptions, ScriptBlock, Code, or CodeFilePath paramet
 65.NOTES
 66    This function is part of the Kestrun PowerShell module and is used to manage Kestrun servers
 67    and their middleware components.
 68#>
 69function Enable-KrExceptionHandling {
 70    [KestrunRuntimeApi('Definition')]
 71    [CmdletBinding(DefaultParameterSetName = 'Default')]
 72    [OutputType([Kestrun.Hosting.KestrunHost])]
 73    param(
 74        [Parameter(ValueFromPipeline = $true)]
 75        [Kestrun.Hosting.KestrunHost] $Server,
 76
 77        # Redirect
 78        [Parameter(Mandatory = $true, ParameterSetName = 'ExceptionHandlingPath')]
 79        [string] $ExceptionHandlingPath,
 80        [Parameter(ParameterSetName = 'LanguageOptions')]
 81        [Parameter(ParameterSetName = 'ScriptBlock')]
 82        [Parameter(ParameterSetName = 'Code')]
 83        [Parameter(ParameterSetName = 'CodeFilePath')]
 84        [Parameter(ParameterSetName = 'ExceptionHandlingPath')]
 85        [switch] $CreateScopeForErrors,
 86        [Parameter(ParameterSetName = 'LanguageOptions')]
 87        [Parameter(ParameterSetName = 'ScriptBlock')]
 88        [Parameter(ParameterSetName = 'Code')]
 89        [Parameter(ParameterSetName = 'CodeFilePath')]
 90        [Parameter(ParameterSetName = 'ExceptionHandlingPath')]
 91        [switch] $AllowStatusCode404Response,
 92
 93        [Parameter(ParameterSetName = 'Json')]
 94        [switch] $IncludeDetailsInDevelopment,
 95        [Parameter(ParameterSetName = 'Json')]
 96        [switch] $UseProblemDetails,
 97        [Parameter(ParameterSetName = 'Json')]
 98        [switch] $Compress,
 99
 100        [Parameter(Mandatory = $true, ParameterSetName = 'DeveloperExceptionPage')]
 101        [switch] $DeveloperExceptionPage,
 102        [Parameter(ParameterSetName = 'DeveloperExceptionPage')]
 103        [int] $SourceCodeLineCount,
 104        [Parameter(ParameterSetName = 'DeveloperExceptionPage')]
 105        [string] $SourceCodePath,
 106
 107        # Custom via LanguageOptions or ScriptBlock
 108        [Parameter(ParameterSetName = 'LanguageOptions')]
 109        [Kestrun.Hosting.Options.LanguageOptions] $LanguageOptions,
 110
 111        [Parameter(ParameterSetName = 'ScriptBlock')]
 112        [scriptblock] $ScriptBlock,
 113
 114        [Parameter(Mandatory = $true, ParameterSetName = 'Code')]
 115        [Alias('CodeBlock')]
 116        [string]$Code,
 117        [Parameter(Mandatory = $true, ParameterSetName = 'Code')]
 118        [Kestrun.Scripting.ScriptLanguage]$Language,
 119
 120        [Parameter(Mandatory = $true, ParameterSetName = 'CodeFilePath')]
 121        [string]$CodeFilePath,
 122
 123        [Parameter(ParameterSetName = 'ScriptBlock')]
 124        [Parameter(ParameterSetName = 'Code')]
 125        [Parameter(ParameterSetName = 'CodeFilePath')]
 126        [System.Reflection.Assembly[]]$ExtraRefs = $null,
 127
 128        [Parameter(ParameterSetName = 'ScriptBlock')]
 129        [Parameter(ParameterSetName = 'Code')]
 130        [Parameter(ParameterSetName = 'CodeFilePath')]
 131        [hashtable]$Arguments,
 132
 133        [Parameter(ParameterSetName = 'ScriptBlock')]
 134        [Parameter(ParameterSetName = 'Code')]
 135        [Parameter(ParameterSetName = 'CodeFilePath')]
 136        [string[]]$ExtraImports = $null,
 137
 138        [switch] $PassThru
 139    )
 140    begin {
 0141        $Server = Resolve-KestrunServer -Server $Server
 142    }
 143    process {
 0144        $exceptionOptions = [Kestrun.Hosting.Options.ExceptionOptions]::new($Server)
 145
 146        # Map direct ExceptionOptions properties from parameters
 0147        if ($PSBoundParameters.ContainsKey('CreateScopeForErrors')) {
 0148            $exceptionOptions.CreateScopeForErrors = $CreateScopeForErrors.IsPresent
 149        }
 0150        if ($PSBoundParameters.ContainsKey('AllowStatusCode404Response')) {
 0151            $exceptionOptions.AllowStatusCode404Response = $AllowStatusCode404Response.IsPresent
 152        }
 0153        if ($PSCmdlet.ParameterSetName -eq 'ExceptionHandlingPath') {
 0154            $exceptionOptions.ExceptionHandlingPath = [Microsoft.AspNetCore.Http.PathString]::new($ExceptionHandlingPath
 0155        } elseif ($PSCmdlet.ParameterSetName -eq 'Json') {
 156            # If using JSON fallback, set the options accordingly
 157            # If using the JSON fallback, set up the built-in JSON handler
 0158            $exceptionOptions.UseJsonExceptionHandler($UseProblemDetails.IsPresent, $IncludeDetailsInDevelopment.IsPrese
 0159        } elseif ($PSCmdlet.ParameterSetName -eq 'LanguageOptions') {
 160            # If using LanguageOptions, assign it directly
 0161            $exceptionOptions.LanguageOptions = $LanguageOptions
 0162        } elseif ($PSCmdlet.ParameterSetName -eq 'DeveloperExceptionPage') {
 163            # Warn if not in Development environment
 0164            if (-not (Test-KrDebugContext)) {
 0165                if (Test-KrLogger) {
 0166                    Write-KrLog -Level Warning -Message 'DeveloperExceptionPage is typically used in Development environ
 167                } else {
 0168                    Write-Warning -Message 'DeveloperExceptionPage is typically used in Development environment. Current
 169                }
 170            }
 171            # If using Developer Exception Page, set up the options accordingly
 0172            $exceptionOptions.DeveloperExceptionPageOptions = [Microsoft.AspNetCore.Builder.DeveloperExceptionPageOption
 173            # Configure Developer Exception Page options if specified
 0174            if ($PSBoundParameters.ContainsKey('SourceCodeLineCount')) {
 0175                $exceptionOptions.DeveloperExceptionPageOptions.SourceCodeLineCount = $SourceCodeLineCount
 176            }
 0177            if ($PSBoundParameters.ContainsKey('SourceCodePath')) {
 0178                $exceptionOptions.DeveloperExceptionPageOptions.FileProvider = [Microsoft.Extensions.FileProviders.Physi
 179            }
 0180        } elseif ($PSCmdlet.ParameterSetName -ne 'Default') {
 0181            $lo = [Kestrun.Hosting.Options.LanguageOptions]::new()
 0182            $lo.ExtraImports = $ExtraImports
 0183            $lo.ExtraRefs = $ExtraRefs
 0184            if ($null -ne $Arguments) {
 0185                $dict = [System.Collections.Generic.Dictionary[string, object]]::new()
 0186                foreach ($key in $Arguments.Keys) {
 0187                    $dict[$key] = $Arguments[$key]
 188                }
 0189                $lo.Arguments = $dict
 190            }
 191
 0192            switch ($PSCmdlet.ParameterSetName) {
 193                'ScriptBlock' {
 0194                    $lo.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 0195                    $lo.Code = $ScriptBlock.ToString()
 196                }
 197                'Code' {
 0198                    $lo.Language = $Language
 0199                    $lo.Code = $Code
 200                }
 201                'CodeFilePath' {
 0202                    if (-not (Test-Path -Path $CodeFilePath)) {
 0203                        throw "The specified code file path does not exist: $CodeFilePath"
 204                    }
 0205                    $extension = Split-Path -Path $CodeFilePath -Extension
 0206                    switch ($extension) {
 207                        '.ps1' {
 0208                            $lo.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 209                        }
 210                        '.cs' {
 0211                            $lo.Language = [Kestrun.Scripting.ScriptLanguage]::CSharp
 212                        }
 213                        '.vb' {
 0214                            $lo.Language = [Kestrun.Scripting.ScriptLanguage]::VisualBasic
 215                        }
 216                        default {
 0217                            throw "Unsupported '$extension' code file extension."
 218                        }
 219                    }
 0220                    $lo.Code = Get-Content -Path $CodeFilePath -Raw
 221                }
 222                default {
 0223                    throw "Unrecognized ParameterSetName: $($PSCmdlet.ParameterSetName)"
 224                }
 225            }
 0226            $exceptionOptions.LanguageOptions = $lo
 227        }
 228
 229
 230        # Assign the configured options to the server instance
 0231        $Server.ExceptionOptions = $exceptionOptions
 232
 0233        if ($PassThru.IsPresent) {
 234            # if the PassThru switch is specified, return the modified server instance
 0235            return $Server
 236        }
 237    }
 238}

Methods/Properties

Enable-KrExceptionHandling()