< 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@6135d944f8787fb570e4dfbacac6e80312799a86
Line coverage
0%
Covered lines: 0
Uncovered lines: 48
Coverable lines: 48
Total lines: 218
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 12/01/2025 - 20:55:19 Line coverage: 0% (0/50) Total lines: 238 Tag: Kestrun/Kestrun@638a27c2dd54103f693f023b6ba5f56a884caafa05/09/2026 - 21:51:36 Line coverage: 0% (0/48) Total lines: 218 Tag: Kestrun/Kestrun@6b24c7512a1bad61723a28d32446de0aa658293e

Coverage delta

Coverage delta 1 -1

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 ExceptionHandlingPath
 8    The path to re-execute when an exception occurs (e.g., '/error').
 9.PARAMETER CreateScopeForErrors
 10    If specified, creates a new scope for handling errors.
 11.PARAMETER AllowStatusCode404Response
 12    If specified, allows handling of 404 status code responses.
 13.PARAMETER IncludeDetailsInDevelopment
 14    If specified, includes detailed error information when the environment is set to Development.
 15.PARAMETER UseProblemDetails
 16    If specified, formats error responses using the Problem Details standard (RFC 7807).
 17.PARAMETER Compress
 18    If specified, compress the json response for error handling.
 19.PARAMETER DeveloperExceptionPage
 20    If specified, enables the Developer Exception Page middleware with default options.
 21.PARAMETER SourceCodeLineCount
 22    The number of source code lines to display around the error line in the Developer Exception Page.
 23.PARAMETER SourceCodePath
 24    The base path to use for locating source code files in the Developer Exception Page.
 25.PARAMETER LanguageOptions
 26    A LanguageOptions object defining the scripting language, code, references, imports, and arguments
 27    for custom error handling logic.
 28.PARAMETER ScriptBlock
 29    A PowerShell script block to execute for custom error handling logic.
 30.PARAMETER Code
 31    A string containing the code to execute for custom error handling logic.
 32.PARAMETER Language
 33    The scripting language of the provided code (e.g., PowerShell, CSharp, VisualBasic).
 34.PARAMETER CodeFilePath
 35    The file path to a script file containing the code to execute for custom error handling logic.
 36.PARAMETER ExtraRefs
 37    An array of additional assemblies to reference when executing the custom error handling code.
 38.PARAMETER Arguments
 39    A hashtable of arguments to pass to the custom error handling code.
 40.PARAMETER ExtraImports
 41    An array of additional namespaces to import when executing the custom error handling code.
 42.EXAMPLE
 43    Enable-KrExceptionHandling -ExceptionHandlingPath '/error' -CreateScopeForErrors -AllowStatusCode404Response -PassTh
 44    Enables exception handling middleware on the default Kestrun server instance,
 45    re-executing requests to '/error' when exceptions occur, creating a scope for error handling,
 46    and allowing handling of 404 status code responses. The modified server instance is returned.
 47.EXAMPLE
 48    Enable-KrExceptionHandling -Server $myServer -DeveloperExceptionPage -SourceCodeLineCount 10 -SourceCodePath 'C:\MyA
 49    Enables the Developer Exception Page middleware on the specified Kestrun server instance,
 50    displaying 10 lines of source code around the error line and using 'C:\MyApp' as the base path for source files.
 51.EXAMPLE
 52    $langOptions = [Kestrun.Hosting.Options.LanguageOptions]::new()
 53    $langOptions.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 54    $langOptions.Code = { param($exception) "An error occurred: $($exception.Message)" }
 55    Enable-KrExceptionHandling -Server $myServer -LanguageOptions $langOptions
 56    Enables custom exception handling on the specified Kestrun server instance,
 57    executing the provided PowerShell code block when an exception occurs. The code block receives the exception object 
 58    The custom error handling logic can be defined using the LanguageOptions, ScriptBlock, Code, or CodeFilePath paramet
 59.NOTES
 60    This function is part of the Kestrun PowerShell module and is used to manage Kestrun servers
 61    and their middleware components.
 62#>
 63function Enable-KrExceptionHandling {
 64    [KestrunRuntimeApi('Definition')]
 65    [CmdletBinding(DefaultParameterSetName = 'Default')]
 66    param(
 67        # Redirect
 68        [Parameter(Mandatory = $true, ParameterSetName = 'ExceptionHandlingPath')]
 69        [string] $ExceptionHandlingPath,
 70        [Parameter(ParameterSetName = 'LanguageOptions')]
 71        [Parameter(ParameterSetName = 'ScriptBlock')]
 72        [Parameter(ParameterSetName = 'Code')]
 73        [Parameter(ParameterSetName = 'CodeFilePath')]
 74        [Parameter(ParameterSetName = 'ExceptionHandlingPath')]
 75        [switch] $CreateScopeForErrors,
 76        [Parameter(ParameterSetName = 'LanguageOptions')]
 77        [Parameter(ParameterSetName = 'ScriptBlock')]
 78        [Parameter(ParameterSetName = 'Code')]
 79        [Parameter(ParameterSetName = 'CodeFilePath')]
 80        [Parameter(ParameterSetName = 'ExceptionHandlingPath')]
 81        [switch] $AllowStatusCode404Response,
 82
 83        [Parameter(ParameterSetName = 'Json')]
 84        [switch] $IncludeDetailsInDevelopment,
 85        [Parameter(ParameterSetName = 'Json')]
 86        [switch] $UseProblemDetails,
 87        [Parameter(ParameterSetName = 'Json')]
 88        [switch] $Compress,
 89
 90        [Parameter(Mandatory = $true, ParameterSetName = 'DeveloperExceptionPage')]
 91        [switch] $DeveloperExceptionPage,
 92        [Parameter(ParameterSetName = 'DeveloperExceptionPage')]
 93        [int] $SourceCodeLineCount,
 94        [Parameter(ParameterSetName = 'DeveloperExceptionPage')]
 95        [string] $SourceCodePath,
 96
 97        # Custom via LanguageOptions or ScriptBlock
 98        [Parameter(ParameterSetName = 'LanguageOptions')]
 99        [Kestrun.Hosting.Options.LanguageOptions] $LanguageOptions,
 100
 101        [Parameter(ParameterSetName = 'ScriptBlock')]
 102        [scriptblock] $ScriptBlock,
 103
 104        [Parameter(Mandatory = $true, ParameterSetName = 'Code')]
 105        [Alias('CodeBlock')]
 106        [string]$Code,
 107        [Parameter(Mandatory = $true, ParameterSetName = 'Code')]
 108        [Kestrun.Scripting.ScriptLanguage]$Language,
 109
 110        [Parameter(Mandatory = $true, ParameterSetName = 'CodeFilePath')]
 111        [string]$CodeFilePath,
 112
 113        [Parameter(ParameterSetName = 'ScriptBlock')]
 114        [Parameter(ParameterSetName = 'Code')]
 115        [Parameter(ParameterSetName = 'CodeFilePath')]
 116        [System.Reflection.Assembly[]]$ExtraRefs = $null,
 117
 118        [Parameter(ParameterSetName = 'ScriptBlock')]
 119        [Parameter(ParameterSetName = 'Code')]
 120        [Parameter(ParameterSetName = 'CodeFilePath')]
 121        [hashtable]$Arguments,
 122
 123        [Parameter(ParameterSetName = 'ScriptBlock')]
 124        [Parameter(ParameterSetName = 'Code')]
 125        [Parameter(ParameterSetName = 'CodeFilePath')]
 126        [string[]]$ExtraImports = $null
 127    )
 128    # Ensure the server instance is resolved
 0129    $Server = Resolve-KestrunServer
 130
 0131    $exceptionOptions = [Kestrun.Hosting.Options.ExceptionOptions]::new($Server)
 132
 133    # Map direct ExceptionOptions properties from parameters
 0134    if ($PSBoundParameters.ContainsKey('CreateScopeForErrors')) {
 0135        $exceptionOptions.CreateScopeForErrors = $CreateScopeForErrors.IsPresent
 136    }
 0137    if ($PSBoundParameters.ContainsKey('AllowStatusCode404Response')) {
 0138        $exceptionOptions.AllowStatusCode404Response = $AllowStatusCode404Response.IsPresent
 139    }
 0140    if ($PSCmdlet.ParameterSetName -eq 'ExceptionHandlingPath') {
 0141        $exceptionOptions.ExceptionHandlingPath = [Microsoft.AspNetCore.Http.PathString]::new($ExceptionHandlingPath)
 0142    } elseif ($PSCmdlet.ParameterSetName -eq 'Json') {
 143        # If using JSON fallback, set the options accordingly
 144        # If using the JSON fallback, set up the built-in JSON handler
 0145        $exceptionOptions.UseJsonExceptionHandler($UseProblemDetails.IsPresent, $IncludeDetailsInDevelopment.IsPresent, 
 0146    } elseif ($PSCmdlet.ParameterSetName -eq 'LanguageOptions') {
 147        # If using LanguageOptions, assign it directly
 0148        $exceptionOptions.LanguageOptions = $LanguageOptions
 0149    } elseif ($PSCmdlet.ParameterSetName -eq 'DeveloperExceptionPage') {
 150        # Warn if not in Development environment
 0151        if (-not (Test-KrDebugContext)) {
 0152            if (Test-KrLogger) {
 0153                Write-KrLog -Level Warning -Message 'DeveloperExceptionPage is typically used in Development environment
 154            } else {
 0155                Write-Warning -Message 'DeveloperExceptionPage is typically used in Development environment. Current env
 156            }
 157        }
 158        # If using Developer Exception Page, set up the options accordingly
 0159        $exceptionOptions.DeveloperExceptionPageOptions = [Microsoft.AspNetCore.Builder.DeveloperExceptionPageOptions]::
 160        # Configure Developer Exception Page options if specified
 0161        if ($PSBoundParameters.ContainsKey('SourceCodeLineCount')) {
 0162            $exceptionOptions.DeveloperExceptionPageOptions.SourceCodeLineCount = $SourceCodeLineCount
 163        }
 0164        if ($PSBoundParameters.ContainsKey('SourceCodePath')) {
 0165            $exceptionOptions.DeveloperExceptionPageOptions.FileProvider = [Microsoft.Extensions.FileProviders.PhysicalF
 166        }
 0167    } elseif ($PSCmdlet.ParameterSetName -ne 'Default') {
 0168        $lo = [Kestrun.Hosting.Options.LanguageOptions]::new()
 0169        $lo.ExtraImports = $ExtraImports
 0170        $lo.ExtraRefs = $ExtraRefs
 0171        if ($null -ne $Arguments) {
 0172            $dict = [System.Collections.Generic.Dictionary[string, object]]::new()
 0173            foreach ($key in $Arguments.Keys) {
 0174                $dict[$key] = $Arguments[$key]
 175            }
 0176            $lo.Arguments = $dict
 177        }
 178
 0179        switch ($PSCmdlet.ParameterSetName) {
 180            'ScriptBlock' {
 0181                $lo.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 0182                $lo.Code = $ScriptBlock.ToString()
 183            }
 184            'Code' {
 0185                $lo.Language = $Language
 0186                $lo.Code = $Code
 187            }
 188            'CodeFilePath' {
 0189                if (-not (Test-Path -Path $CodeFilePath)) {
 0190                    throw "The specified code file path does not exist: $CodeFilePath"
 191                }
 0192                $extension = Split-Path -Path $CodeFilePath -Extension
 0193                switch ($extension) {
 194                    '.ps1' {
 0195                        $lo.Language = [Kestrun.Scripting.ScriptLanguage]::PowerShell
 196                    }
 197                    '.cs' {
 0198                        $lo.Language = [Kestrun.Scripting.ScriptLanguage]::CSharp
 199                    }
 200                    '.vb' {
 0201                        $lo.Language = [Kestrun.Scripting.ScriptLanguage]::VisualBasic
 202                    }
 203                    default {
 0204                        throw "Unsupported '$extension' code file extension."
 205                    }
 206                }
 0207                $lo.Code = Get-Content -Path $CodeFilePath -Raw
 208            }
 209            default {
 0210                throw "Unrecognized ParameterSetName: $($PSCmdlet.ParameterSetName)"
 211            }
 212        }
 0213        $exceptionOptions.LanguageOptions = $lo
 214    }
 215
 216    # Assign the configured options to the server instance
 0217    $Server.ExceptionOptions = $exceptionOptions
 218}

Methods/Properties

Enable-KrExceptionHandling()