| | | 1 | | /******************************************************************************** |
| | | 2 | | * NanoRouteExceptionExtensions.cs * |
| | | 3 | | * * |
| | | 4 | | * Author: Denes Solti * |
| | | 5 | | ********************************************************************************/ |
| | | 6 | | using System; |
| | | 7 | | using System.Diagnostics; |
| | | 8 | | using System.Diagnostics.CodeAnalysis; |
| | | 9 | | using System.Collections.Frozen; |
| | | 10 | | using System.Collections.Generic; |
| | | 11 | | using System.Linq; |
| | | 12 | | using System.Net; |
| | | 13 | | using System.Net.Http; |
| | | 14 | | |
| | | 15 | | namespace NanoRoute |
| | | 16 | | { |
| | | 17 | | using Internals; |
| | | 18 | | using Properties; |
| | | 19 | | |
| | | 20 | | /// <summary> |
| | | 21 | | /// Converts an unexpected exception into an enriched <see cref="HttpRequestException"/>. |
| | | 22 | | /// </summary> |
| | | 23 | | /// <param name="exception">The exception thrown by a later handler in the routing pipeline.</param> |
| | | 24 | | /// <returns> |
| | | 25 | | /// The <see cref="HttpRequestException"/> that should be thrown by the exception-handling middleware. |
| | | 26 | | /// </returns> |
| | | 27 | | /// <remarks> |
| | | 28 | | /// Normalizers are configured with <see cref="ExceptionHandlingOptions.Map{TException}(TypedExceptionNormalizer{TEx |
| | | 29 | | /// Existing <see cref="HttpRequestException"/> and <see cref="OperationCanceledException"/> values are not |
| | | 30 | | /// normalized by <see cref="NanoRouteExceptionExtensions.AddExceptionHandler{TBuilder}(TBuilder)"/>. |
| | | 31 | | /// Exceptions thrown by a normalizer propagate from the exception-handling middleware. |
| | | 32 | | /// </remarks> |
| | | 33 | | /// <example> |
| | | 34 | | /// <code> |
| | | 35 | | /// builder.AddExceptionHandler(options => options.Map<InvalidOperationException> |
| | | 36 | | /// ( |
| | | 37 | | /// static ex => new HttpRequestException("Bad state", ex, HttpStatusCode.Conflict) |
| | | 38 | | /// )); |
| | | 39 | | /// </code> |
| | | 40 | | /// </example> |
| | | 41 | | public delegate HttpRequestException ExceptionNormalizer(Exception exception); |
| | | 42 | | |
| | | 43 | | /// <summary> |
| | | 44 | | /// Converts an unexpected exception of a registered type into an enriched <see cref="HttpRequestException"/>. |
| | | 45 | | /// </summary> |
| | | 46 | | /// <typeparam name="TException">The exception type handled by the normalizer.</typeparam> |
| | | 47 | | /// <param name="exception">The exception thrown by a later handler in the routing pipeline.</param> |
| | | 48 | | /// <returns> |
| | | 49 | | /// The <see cref="HttpRequestException"/> that should be thrown by the exception-handling middleware. |
| | | 50 | | /// </returns> |
| | | 51 | | /// <remarks> |
| | | 52 | | /// Use this delegate with <see cref="ExceptionHandlingOptions.Map{TException}(TypedExceptionNormalizer{TException}) |
| | | 53 | | /// to register typed normalizers without manually casting from <see cref="Exception"/>. Exception handlers |
| | | 54 | | /// check the exact runtime type first, then walk base exception types, so a base-type normalizer handles |
| | | 55 | | /// derived exceptions unless a more specific normalizer is registered. |
| | | 56 | | /// </remarks> |
| | | 57 | | /// <example> |
| | | 58 | | /// <code> |
| | | 59 | | /// options.Map<InvalidOperationException> |
| | | 60 | | /// ( |
| | | 61 | | /// static ex => new HttpRequestException("Bad state", ex, HttpStatusCode.Conflict) |
| | | 62 | | /// ); |
| | | 63 | | /// </code> |
| | | 64 | | /// </example> |
| | | 65 | | public delegate HttpRequestException TypedExceptionNormalizer<TException>(TException exception) where TException : E |
| | | 66 | | |
| | | 67 | | /// <summary> |
| | | 68 | | /// Configures exception normalizers for a single exception-handling middleware registration. |
| | | 69 | | /// </summary> |
| | | 70 | | /// <remarks> |
| | | 71 | | /// New instances include the built-in <see cref="AggregateException"/> normalizer, which expands inner exceptions |
| | | 72 | | /// into developer messages. Each call to <see cref="Map{TException}(TypedExceptionNormalizer{TException})"/> adds |
| | | 73 | | /// or replaces the normalizer for that exception type. |
| | | 74 | | /// </remarks> |
| | | 75 | | /// <example> |
| | | 76 | | /// <code> |
| | | 77 | | /// builder.AddExceptionHandler(options => options |
| | | 78 | | /// .Map<InvalidOperationException>(static ex => new HttpRequestException("Conflict", ex, HttpStatusCod |
| | | 79 | | /// </code> |
| | | 80 | | /// </example> |
| | | 81 | | public class ExceptionHandlingOptions |
| | | 82 | | { |
| | | 83 | | /// <summary> |
| | | 84 | | /// Initializes an exception-handling options instance with the built-in normalizers. |
| | | 85 | | /// </summary> |
| | | 86 | | /// <remarks> |
| | | 87 | | /// The default options include an <see cref="AggregateException"/> normalizer that expands inner exceptions |
| | | 88 | | /// into developer messages. |
| | | 89 | | /// </remarks> |
| | | 90 | | /// <example> |
| | | 91 | | /// <code> |
| | | 92 | | /// ExceptionHandlingOptions options = new(); |
| | | 93 | | /// </code> |
| | | 94 | | /// </example> |
| | 1 | 95 | | public ExceptionHandlingOptions() |
| | 1 | 96 | | { |
| | 1 | 97 | | Map<AggregateException> |
| | 1 | 98 | | ( |
| | 1 | 99 | | static ex => |
| | 1 | 100 | | { |
| | 1 | 101 | | HttpRequestException.Throw |
| | 1 | 102 | | ( |
| | 1 | 103 | | HttpStatusCode.InternalServerError, |
| | 1 | 104 | | Resources.ERR_INTERNAL_ERROR, |
| | 1 | 105 | | ex, |
| | 1 | 106 | | developerMessages: ex.InnerExceptions.Select(static ex => ex.ToString()) |
| | 1 | 107 | | ); |
| | 1 | 108 | | return null!; |
| | 1 | 109 | | } |
| | 1 | 110 | | ); |
| | 1 | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary> |
| | | 114 | | /// Adds or replaces the normalizer used for <typeparamref name="TException"/> and its derived exception types. |
| | | 115 | | /// </summary> |
| | | 116 | | /// <typeparam name="TException">The exception type handled by <paramref name="normalizer"/>.</typeparam> |
| | | 117 | | /// <param name="normalizer">The normalizer that converts the exception into an enriched <see cref="HttpRequestE |
| | | 118 | | /// <returns>The current <see cref="ExceptionHandlingOptions"/> instance.</returns> |
| | | 119 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="normalizer"/> is <see langword="null"/>. |
| | | 120 | | /// <example> |
| | | 121 | | /// <code> |
| | | 122 | | /// options.Map<InvalidOperationException>(static ex => new HttpRequestException("Conflict", ex, HttpSt |
| | | 123 | | /// </code> |
| | | 124 | | /// </example> |
| | | 125 | | public void Map<TException>(TypedExceptionNormalizer<TException> normalizer) where TException : Exception |
| | 1 | 126 | | { |
| | 1 | 127 | | Ensure.NotNull(normalizer); |
| | | 128 | | |
| | 1 | 129 | | ExceptionNormalizers.Add(typeof(TException), ex => normalizer((TException) ex)); |
| | 1 | 130 | | } |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// Gets or sets the exception normalizers keyed by exception type. |
| | | 134 | | /// </summary> |
| | | 135 | | /// <remarks> |
| | | 136 | | /// Exception handlers check the thrown exception's exact runtime type first, then walk base exception types |
| | | 137 | | /// until a normalizer is found. Use <see cref="Map{TException}(TypedExceptionNormalizer{TException})"/> for |
| | | 138 | | /// typed registration, or replace this dictionary when a prebuilt normalizer set is easier to compose. |
| | | 139 | | /// </remarks> |
| | | 140 | | /// <exception cref="ArgumentNullException">Thrown when the assigned value is <see langword="null"/>.</exception |
| | | 141 | | /// <example> |
| | | 142 | | /// <code> |
| | | 143 | | /// options.ExceptionNormalizers = options.ExceptionNormalizers.SetItem |
| | | 144 | | /// ( |
| | | 145 | | /// typeof(InvalidOperationException), |
| | | 146 | | /// static ex => new HttpRequestException("Conflict", ex, HttpStatusCode.Conflict) |
| | | 147 | | /// ); |
| | | 148 | | /// </code> |
| | | 149 | | /// </example> |
| | | 150 | | public Dictionary<Type, ExceptionNormalizer> ExceptionNormalizers |
| | | 151 | | { |
| | | 152 | | get; |
| | | 153 | | set |
| | 1 | 154 | | { |
| | 1 | 155 | | Ensure.NotNull(value); |
| | 0 | 156 | | field = value; |
| | 0 | 157 | | } |
| | 1 | 158 | | } = []; |
| | | 159 | | } |
| | | 160 | | |
| | | 161 | | /// <summary> |
| | | 162 | | /// Adds helpers for normalizing exceptions and extracting structured error details. |
| | | 163 | | /// </summary> |
| | | 164 | | /// <example> |
| | | 165 | | /// <code> |
| | | 166 | | /// builder.AddExceptionHandler(); |
| | | 167 | | /// </code> |
| | | 168 | | /// </example> |
| | | 169 | | public static class NanoRouteExceptionExtensions |
| | | 170 | | { |
| | | 171 | | #region Private |
| | | 172 | | [DebuggerBrowsable(DebuggerBrowsableState.Never)] |
| | | 173 | | private static readonly Action<ExceptionHandlingOptions> s_noopConfigure = static _ => { }; |
| | | 174 | | |
| | | 175 | | private const string |
| | | 176 | | ErrorsName = "Errors", |
| | | 177 | | DeveloperMessagesName = "DeveloperMessages", |
| | | 178 | | StatusName = "StatusCode"; |
| | | 179 | | |
| | | 180 | | private static T? GetProperty<T>(HttpRequestException requestException, string key) |
| | | 181 | | { |
| | | 182 | | Ensure.NotNull(requestException); |
| | | 183 | | |
| | | 184 | | if (!requestException.Data.Contains(key)) |
| | | 185 | | return default; |
| | | 186 | | |
| | | 187 | | return (T) requestException.Data[key]; |
| | | 188 | | } |
| | | 189 | | |
| | | 190 | | private static void SetProperty(HttpRequestException requestException, string key, object? value) |
| | | 191 | | { |
| | | 192 | | Ensure.NotNull(requestException); |
| | | 193 | | if (value is null) |
| | | 194 | | requestException.Data.Remove(key); |
| | | 195 | | else |
| | | 196 | | requestException.Data[key] = value; |
| | | 197 | | } |
| | | 198 | | #endregion |
| | | 199 | | |
| | | 200 | | extension<TBuilder>(TBuilder routeScopeBuilder) where TBuilder : RouteScopeBuilder |
| | | 201 | | { |
| | | 202 | | /// <summary> |
| | | 203 | | /// Adds an exception-handling middleware for all supported HTTP methods. |
| | | 204 | | /// </summary> |
| | | 205 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 206 | | /// <remarks> |
| | | 207 | | /// The inserted middleware converts unexpected exceptions into <see cref="HttpRequestException"/> values |
| | | 208 | | /// with normalized status codes and diagnostic payloads. Existing <see cref="HttpRequestException"/> |
| | | 209 | | /// values are allowed to flow through unchanged. <see cref="OperationCanceledException"/> is intentionally |
| | | 210 | | /// not normalized so caller-driven cancellation can propagate unchanged. |
| | | 211 | | /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the middleware |
| | | 212 | | /// is bound to the whole current builder scope for all supported HTTP methods. |
| | | 213 | | /// </remarks> |
| | | 214 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> is <see langwor |
| | | 215 | | /// <example> |
| | | 216 | | /// <code> |
| | | 217 | | /// builder.AddExceptionHandler(); |
| | | 218 | | /// </code> |
| | | 219 | | /// </example> |
| | | 220 | | public TBuilder AddExceptionHandler() => |
| | | 221 | | routeScopeBuilder.AddExceptionHandler(HttpVerb.Names, RouteScopeBuilder.CurrentPrefix, s_noopConfigure); |
| | | 222 | | |
| | | 223 | | /// <summary> |
| | | 224 | | /// Adds an exception-handling middleware for all supported HTTP methods. |
| | | 225 | | /// </summary> |
| | | 226 | | /// <param name="configure">Configures normalizers for this exception-handling middleware.</param> |
| | | 227 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 228 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> or <paramref na |
| | | 229 | | /// <example> |
| | | 230 | | /// <code> |
| | | 231 | | /// builder.AddExceptionHandler(options => options.Map<InvalidOperationException> |
| | | 232 | | /// ( |
| | | 233 | | /// static ex => new HttpRequestException("Conflict", ex, HttpStatusCode.Conflict) |
| | | 234 | | /// )); |
| | | 235 | | /// </code> |
| | | 236 | | /// </example> |
| | | 237 | | public TBuilder AddExceptionHandler(Action<ExceptionHandlingOptions> configure) => |
| | | 238 | | routeScopeBuilder.AddExceptionHandler(HttpVerb.Names, RouteScopeBuilder.CurrentPrefix, configure); |
| | | 239 | | |
| | | 240 | | /// <summary> |
| | | 241 | | /// Adds an exception-handling middleware for all supported HTTP methods. |
| | | 242 | | /// </summary> |
| | | 243 | | /// <param name="pattern"> |
| | | 244 | | /// The route pattern where the exception-handling middleware should be inserted. Use <c>/</c> to apply it |
| | | 245 | | /// to the whole pipeline, or a narrower prefix/exact pattern to scope normalization to selected routes. |
| | | 246 | | /// </param> |
| | | 247 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 248 | | /// <remarks> |
| | | 249 | | /// The inserted middleware converts unexpected exceptions into <see cref="HttpRequestException"/> values |
| | | 250 | | /// with normalized status codes and diagnostic payloads. Existing <see cref="HttpRequestException"/> |
| | | 251 | | /// values are allowed to flow through unchanged. <see cref="OperationCanceledException"/> is intentionally |
| | | 252 | | /// not normalized so caller-driven cancellation can propagate unchanged. |
| | | 253 | | /// </remarks> |
| | | 254 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> or <paramref na |
| | | 255 | | /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template sy |
| | | 256 | | /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout |
| | | 257 | | /// <example> |
| | | 258 | | /// <code> |
| | | 259 | | /// builder.AddExceptionHandler("/api/*"); |
| | | 260 | | /// </code> |
| | | 261 | | /// </example> |
| | | 262 | | public TBuilder AddExceptionHandler(string pattern) => |
| | | 263 | | routeScopeBuilder.AddExceptionHandler(HttpVerb.Names, pattern, s_noopConfigure); |
| | | 264 | | |
| | | 265 | | /// <summary> |
| | | 266 | | /// Adds an exception-handling middleware for all supported HTTP methods. |
| | | 267 | | /// </summary> |
| | | 268 | | /// <param name="pattern"> |
| | | 269 | | /// The route pattern where the exception-handling middleware should be inserted. Use <c>/</c> to apply it |
| | | 270 | | /// to the whole pipeline, or a narrower prefix/exact pattern to scope normalization to selected routes. |
| | | 271 | | /// </param> |
| | | 272 | | /// <param name="configure">Configures normalizers for this exception-handling middleware.</param> |
| | | 273 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 274 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name |
| | | 275 | | /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template sy |
| | | 276 | | /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout |
| | | 277 | | /// <example> |
| | | 278 | | /// <code> |
| | | 279 | | /// builder.AddExceptionHandler("/api/*", options => options.Map<InvalidOperationException> |
| | | 280 | | /// ( |
| | | 281 | | /// static ex => new HttpRequestException("Conflict", ex, HttpStatusCode.Conflict) |
| | | 282 | | /// )); |
| | | 283 | | /// </code> |
| | | 284 | | /// </example> |
| | | 285 | | public TBuilder AddExceptionHandler(string pattern, Action<ExceptionHandlingOptions> configure) => |
| | | 286 | | routeScopeBuilder.AddExceptionHandler(HttpVerb.Names, pattern, configure); |
| | | 287 | | |
| | | 288 | | /// <summary> |
| | | 289 | | /// Adds an exception-handling middleware for a single HTTP method. |
| | | 290 | | /// </summary> |
| | | 291 | | /// <param name="verb">The HTTP method that should use the exception-handling middleware.</param> |
| | | 292 | | /// <param name="pattern"> |
| | | 293 | | /// The route pattern where the exception-handling middleware should be inserted. Use <c>/</c> to apply it |
| | | 294 | | /// to the whole pipeline, or a narrower prefix/exact pattern to scope normalization to selected routes. |
| | | 295 | | /// </param> |
| | | 296 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 297 | | /// <remarks> |
| | | 298 | | /// The inserted middleware converts unexpected exceptions into <see cref="HttpRequestException"/> values |
| | | 299 | | /// with normalized status codes and diagnostic payloads. Existing <see cref="HttpRequestException"/> |
| | | 300 | | /// values are allowed to flow through unchanged. <see cref="OperationCanceledException"/> is intentionally |
| | | 301 | | /// not normalized so caller-driven cancellation can propagate unchanged. |
| | | 302 | | /// </remarks> |
| | | 303 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name |
| | | 304 | | /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not supported or <paramref na |
| | | 305 | | /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout |
| | | 306 | | /// <example> |
| | | 307 | | /// <code> |
| | | 308 | | /// builder.AddExceptionHandler("GET", "/api/*"); |
| | | 309 | | /// </code> |
| | | 310 | | /// </example> |
| | | 311 | | public TBuilder AddExceptionHandler(string verb, string pattern) => |
| | | 312 | | routeScopeBuilder.AddExceptionHandler([verb], pattern, s_noopConfigure); |
| | | 313 | | |
| | | 314 | | /// <summary> |
| | | 315 | | /// Adds an exception-handling middleware for a single HTTP method. |
| | | 316 | | /// </summary> |
| | | 317 | | /// <param name="verb">The HTTP method that should use the exception-handling middleware.</param> |
| | | 318 | | /// <param name="pattern"> |
| | | 319 | | /// The route pattern where the exception-handling middleware should be inserted. Use <c>/</c> to apply it |
| | | 320 | | /// to the whole pipeline, or a narrower prefix/exact pattern to scope normalization to selected routes. |
| | | 321 | | /// </param> |
| | | 322 | | /// <param name="configure">Configures normalizers for this exception-handling middleware.</param> |
| | | 323 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 324 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name |
| | | 325 | | /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not supported or <paramref na |
| | | 326 | | /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout |
| | | 327 | | /// <example> |
| | | 328 | | /// <code> |
| | | 329 | | /// builder.AddExceptionHandler("GET", "/api/*", options => options.Map<InvalidOperationException> |
| | | 330 | | /// ( |
| | | 331 | | /// static ex => new HttpRequestException("Conflict", ex, HttpStatusCode.Conflict) |
| | | 332 | | /// )); |
| | | 333 | | /// </code> |
| | | 334 | | /// </example> |
| | | 335 | | public TBuilder AddExceptionHandler(string verb, string pattern, Action<ExceptionHandlingOptions> configure) |
| | | 336 | | routeScopeBuilder.AddExceptionHandler([verb /*will be null checked*/], pattern, configure); |
| | | 337 | | |
| | | 338 | | /// <summary> |
| | | 339 | | /// Adds an exception-handling middleware for the selected HTTP methods. |
| | | 340 | | /// </summary> |
| | | 341 | | /// <param name="verbs">The HTTP methods that should use the exception-handling middleware.</param> |
| | | 342 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 343 | | /// <remarks> |
| | | 344 | | /// The inserted middleware converts unexpected exceptions into <see cref="HttpRequestException"/> values |
| | | 345 | | /// with normalized status codes and diagnostic payloads. Existing <see cref="HttpRequestException"/> |
| | | 346 | | /// values are allowed to flow through unchanged. <see cref="OperationCanceledException"/> is intentionally |
| | | 347 | | /// not normalized so caller-driven cancellation can propagate unchanged. |
| | | 348 | | /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the middleware |
| | | 349 | | /// is bound to the whole current builder scope for the selected HTTP methods. |
| | | 350 | | /// </remarks> |
| | | 351 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> or <paramref na |
| | | 352 | | /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not a supported |
| | | 353 | | /// <example> |
| | | 354 | | /// <code> |
| | | 355 | | /// builder.AddExceptionHandler(["GET", "POST"]); |
| | | 356 | | /// </code> |
| | | 357 | | /// </example> |
| | | 358 | | public TBuilder AddExceptionHandler(IEnumerable<string> verbs) => |
| | | 359 | | routeScopeBuilder.AddExceptionHandler(verbs, RouteScopeBuilder.CurrentPrefix, s_noopConfigure); |
| | | 360 | | |
| | | 361 | | /// <summary> |
| | | 362 | | /// Adds an exception-handling middleware for the selected HTTP methods. |
| | | 363 | | /// </summary> |
| | | 364 | | /// <param name="verbs">The HTTP methods that should use the exception-handling middleware.</param> |
| | | 365 | | /// <param name="configure">Configures normalizers for this exception-handling middleware.</param> |
| | | 366 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 367 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name |
| | | 368 | | /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not a supported |
| | | 369 | | /// <example> |
| | | 370 | | /// <code> |
| | | 371 | | /// builder.AddExceptionHandler(["GET", "POST"], options => options.Map<InvalidOperationException> |
| | | 372 | | /// ( |
| | | 373 | | /// static ex => new HttpRequestException("Conflict", ex, HttpStatusCode.Conflict) |
| | | 374 | | /// )); |
| | | 375 | | /// </code> |
| | | 376 | | /// </example> |
| | | 377 | | public TBuilder AddExceptionHandler(IEnumerable<string> verbs, Action<ExceptionHandlingOptions> configure) = |
| | | 378 | | routeScopeBuilder.AddExceptionHandler(verbs, RouteScopeBuilder.CurrentPrefix, configure); |
| | | 379 | | |
| | | 380 | | /// <summary> |
| | | 381 | | /// Adds an exception-handling middleware for the selected HTTP methods. |
| | | 382 | | /// </summary> |
| | | 383 | | /// <param name="verbs">The HTTP methods that should use the exception-handling middleware.</param> |
| | | 384 | | /// <param name="pattern"> |
| | | 385 | | /// The route pattern where the exception-handling middleware should be inserted. Use <c>/</c> to apply it |
| | | 386 | | /// to the whole pipeline, or a narrower prefix/exact pattern to scope normalization to selected routes. |
| | | 387 | | /// </param> |
| | | 388 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 389 | | /// <remarks> |
| | | 390 | | /// The inserted middleware converts unexpected exceptions into <see cref="HttpRequestException"/> values |
| | | 391 | | /// with normalized status codes and diagnostic payloads. Existing <see cref="HttpRequestException"/> |
| | | 392 | | /// values are allowed to flow through unchanged. <see cref="OperationCanceledException"/> is intentionally |
| | | 393 | | /// not normalized so caller-driven cancellation can propagate unchanged. |
| | | 394 | | /// </remarks> |
| | | 395 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name |
| | | 396 | | /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not supported or |
| | | 397 | | /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout |
| | | 398 | | /// <example> |
| | | 399 | | /// <code> |
| | | 400 | | /// builder.AddExceptionHandler(["POST", "PUT"], "/api/users/*"); |
| | | 401 | | /// </code> |
| | | 402 | | /// </example> |
| | | 403 | | public TBuilder AddExceptionHandler(IEnumerable<string> verbs, string pattern) => |
| | | 404 | | routeScopeBuilder.AddExceptionHandler(verbs, pattern, s_noopConfigure); |
| | | 405 | | |
| | | 406 | | /// <summary> |
| | | 407 | | /// Adds an exception-handling middleware for the selected HTTP methods. |
| | | 408 | | /// </summary> |
| | | 409 | | /// <param name="verbs">The HTTP methods that should use the exception-handling middleware.</param> |
| | | 410 | | /// <param name="pattern"> |
| | | 411 | | /// The route pattern where the exception-handling middleware should be inserted. Use <c>/</c> to apply it |
| | | 412 | | /// to the whole pipeline, or a narrower prefix/exact pattern to scope normalization to selected routes. |
| | | 413 | | /// </param> |
| | | 414 | | /// <param name="configure">Configures normalizers for this exception-handling middleware.</param> |
| | | 415 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 416 | | /// <remarks> |
| | | 417 | | /// The inserted middleware converts unexpected exceptions into <see cref="HttpRequestException"/> values |
| | | 418 | | /// with normalized status codes and diagnostic payloads. Existing <see cref="HttpRequestException"/> |
| | | 419 | | /// values are allowed to flow through unchanged. <see cref="OperationCanceledException"/> is intentionally |
| | | 420 | | /// not normalized so caller-driven cancellation can propagate unchanged. |
| | | 421 | | /// </remarks> |
| | | 422 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name |
| | | 423 | | /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not supported or |
| | | 424 | | /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout |
| | | 425 | | /// <example> |
| | | 426 | | /// <code> |
| | | 427 | | /// builder.AddExceptionHandler(["POST", "PUT"], "/api/users/*", options => options.Map<InvalidOperati |
| | | 428 | | /// ( |
| | | 429 | | /// static ex => new HttpRequestException("Conflict", ex, HttpStatusCode.Conflict) |
| | | 430 | | /// )); |
| | | 431 | | /// </code> |
| | | 432 | | /// </example> |
| | | 433 | | public TBuilder AddExceptionHandler(IEnumerable<string> verbs, string pattern, Action<ExceptionHandlingOptio |
| | | 434 | | { |
| | | 435 | | Ensure.NotNull(configure); |
| | | 436 | | |
| | | 437 | | ExceptionHandlingOptions options = new(); |
| | | 438 | | configure.Invoke(options); |
| | | 439 | | |
| | | 440 | | return routeScopeBuilder.AddExceptionHandler(verbs, pattern, options); |
| | | 441 | | } |
| | | 442 | | |
| | | 443 | | /// <summary> |
| | | 444 | | /// Adds an exception-handling middleware with preconfigured exception normalizers. |
| | | 445 | | /// </summary> |
| | | 446 | | /// <param name="verbs">The HTTP methods that should use the exception-handling middleware.</param> |
| | | 447 | | /// <param name="pattern"> |
| | | 448 | | /// The route pattern where the exception-handling middleware should be inserted. Use <c>/</c> to apply it |
| | | 449 | | /// to the whole pipeline, or a narrower prefix/exact pattern to scope normalization to selected routes. |
| | | 450 | | /// </param> |
| | | 451 | | /// <param name="options">The exception-handling options used by this middleware registration.</param> |
| | | 452 | | /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns> |
| | | 453 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name |
| | | 454 | | /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not supported or |
| | | 455 | | /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout |
| | | 456 | | /// <example> |
| | | 457 | | /// <code> |
| | | 458 | | /// ExceptionHandlingOptions options = new(); |
| | | 459 | | /// options.Map<InvalidOperationException>(static ex => new HttpRequestException("Conflict", ex, Ht |
| | | 460 | | /// |
| | | 461 | | /// builder.AddExceptionHandler(["POST", "PUT"], "/api/users/*", options); |
| | | 462 | | /// </code> |
| | | 463 | | /// </example> |
| | | 464 | | public TBuilder AddExceptionHandler(IEnumerable<string> verbs, string pattern, ExceptionHandlingOptions opti |
| | | 465 | | { |
| | | 466 | | Ensure.NotNull(routeScopeBuilder); |
| | | 467 | | Ensure.NotNull(verbs); |
| | | 468 | | Ensure.NotNull(pattern); |
| | | 469 | | Ensure.NotNull(options); |
| | | 470 | | |
| | | 471 | | FrozenDictionary<Type, ExceptionNormalizer> exceptionNormalizers = options |
| | | 472 | | .ExceptionNormalizers |
| | | 473 | | .ToFrozenDictionary(); |
| | | 474 | | |
| | | 475 | | routeScopeBuilder.AddHandler(verbs, pattern, async (RequestContext context, CallNextHandlerDelegate next |
| | | 476 | | { |
| | | 477 | | try |
| | | 478 | | { |
| | | 479 | | return await next().ConfigureAwait(false); |
| | | 480 | | } |
| | | 481 | | catch (Exception ex) when (ex is not (HttpRequestException or OperationCanceledException /*needs to |
| | | 482 | | { |
| | | 483 | | for (Type exceptionType = ex.GetType(); exceptionType != typeof(object); exceptionType = excepti |
| | | 484 | | if (exceptionNormalizers.TryGetValue(exceptionType, out ExceptionNormalizer? exceptionNormal |
| | | 485 | | throw exceptionNormalizer(ex); |
| | | 486 | | |
| | | 487 | | HttpRequestException.Throw(HttpStatusCode.InternalServerError, Resources.ERR_INTERNAL_ERROR, ex, |
| | | 488 | | return null!; |
| | | 489 | | } |
| | | 490 | | }); |
| | | 491 | | |
| | | 492 | | return routeScopeBuilder; |
| | | 493 | | } |
| | | 494 | | } |
| | | 495 | | |
| | | 496 | | extension(HttpRequestException) |
| | | 497 | | { |
| | | 498 | | /// <summary> |
| | | 499 | | /// Throws an <see cref="HttpRequestException"/> enriched with an HTTP status code and public error messages |
| | | 500 | | /// </summary> |
| | | 501 | | /// <param name="status">The HTTP status code that should be associated with the exception.</param> |
| | | 502 | | /// <param name="title">The human-readable error title.</param> |
| | | 503 | | /// <param name="errors">Optional client-facing error messages that should not contain sensitive data.</para |
| | | 504 | | /// <exception cref="HttpRequestException">Always thrown with the supplied status and error metadata.</excep |
| | | 505 | | /// <example> |
| | | 506 | | /// <code> |
| | | 507 | | /// HttpRequestException.Throw(HttpStatusCode.BadRequest, "Bad Request", "Missing id."); |
| | | 508 | | /// </code> |
| | | 509 | | /// </example> |
| | | 510 | | [DoesNotReturn] |
| | | 511 | | public static void Throw(HttpStatusCode status, string title, params string[] errors) |
| | | 512 | | { |
| | | 513 | | Ensure.NotNull(errors); |
| | | 514 | | |
| | | 515 | | Throw(status, title, null, errors.Length > 0 ? errors : null, null); |
| | | 516 | | } |
| | | 517 | | |
| | | 518 | | /// <summary> |
| | | 519 | | /// Throws an <see cref="HttpRequestException"/> enriched with routing-specific metadata. |
| | | 520 | | /// </summary> |
| | | 521 | | /// <param name="status">The HTTP status code that should be associated with the exception.</param> |
| | | 522 | | /// <param name="title">The human-readable error title.</param> |
| | | 523 | | /// <param name="original">The original exception, if any.</param> |
| | | 524 | | /// <param name="errors">Optional client-facing error messages that should not contain sensitive data.</para |
| | | 525 | | /// <param name="developerMessages">Optional developer-facing messages that may contain sensitive data.</par |
| | | 526 | | /// <exception cref="HttpRequestException">Always thrown with the supplied status and error metadata.</excep |
| | | 527 | | /// <example> |
| | | 528 | | /// <code> |
| | | 529 | | /// Exception original = ... |
| | | 530 | | /// HttpRequestException.Throw |
| | | 531 | | /// ( |
| | | 532 | | /// HttpStatusCode.Conflict, |
| | | 533 | | /// "Conflict", |
| | | 534 | | /// original, |
| | | 535 | | /// errors: ["The resource has changed."], |
| | | 536 | | /// developerMessages: [original.ToString()] |
| | | 537 | | /// ); |
| | | 538 | | /// </code> |
| | | 539 | | /// </example> |
| | | 540 | | [DoesNotReturn] |
| | | 541 | | public static void Throw(HttpStatusCode status, string title, Exception? original = null, IEnumerable<string |
| | | 542 | | { |
| | | 543 | | Ensure.NotNull(title); |
| | | 544 | | |
| | | 545 | | throw new HttpRequestException(title, original) |
| | | 546 | | { |
| | | 547 | | Status = status, |
| | | 548 | | Errors = errors, |
| | | 549 | | DeveloperMessages = developerMessages |
| | | 550 | | }; |
| | | 551 | | } |
| | | 552 | | } |
| | | 553 | | |
| | | 554 | | extension(HttpRequestException requestException) |
| | | 555 | | { |
| | | 556 | | /// <summary> |
| | | 557 | | /// Gets or sets the HTTP status code associated with this exception. |
| | | 558 | | /// </summary> |
| | | 559 | | /// <exception cref="ArgumentNullException">Thrown when the extended exception is <see langword="null"/>.</e |
| | | 560 | | /// <example> |
| | | 561 | | /// <code> |
| | | 562 | | /// exception.Status = HttpStatusCode.BadRequest; |
| | | 563 | | /// HttpStatusCode status = exception.Status; |
| | | 564 | | /// </code> |
| | | 565 | | /// </example> |
| | | 566 | | public HttpStatusCode Status |
| | | 567 | | { |
| | | 568 | | get => GetProperty<HttpStatusCode?>(requestException, StatusName) ?? HttpStatusCode.InternalServerError; |
| | | 569 | | set => SetProperty(requestException, StatusName, value); |
| | | 570 | | } |
| | | 571 | | |
| | | 572 | | /// <summary> |
| | | 573 | | /// Gets or sets the client-facing error messages associated with this exception. |
| | | 574 | | /// </summary> |
| | | 575 | | /// <exception cref="ArgumentNullException">Thrown when the extended exception is <see langword="null"/>.</e |
| | | 576 | | /// <example> |
| | | 577 | | /// <code> |
| | | 578 | | /// exception.Errors = ["Missing id."]; |
| | | 579 | | /// IEnumerable<string>? errors = exception.Errors; |
| | | 580 | | /// </code> |
| | | 581 | | /// </example> |
| | | 582 | | public IEnumerable<string>? Errors |
| | | 583 | | { |
| | | 584 | | get => GetProperty<IEnumerable<string>>(requestException, ErrorsName); |
| | | 585 | | |
| | | 586 | | // On .NET Framework, Data members must be serializable; string[] is. |
| | | 587 | | set => SetProperty(requestException, ErrorsName, value?.ToArray()); |
| | | 588 | | } |
| | | 589 | | |
| | | 590 | | /// <summary> |
| | | 591 | | /// Gets or sets the developer-facing diagnostic messages associated with this exception. |
| | | 592 | | /// </summary> |
| | | 593 | | /// <exception cref="ArgumentNullException">Thrown when the extended exception is <see langword="null"/>.</e |
| | | 594 | | /// <example> |
| | | 595 | | /// <code> |
| | | 596 | | /// exception.DeveloperMessages = [original.ToString()]; |
| | | 597 | | /// IEnumerable<string>? messages = exception.DeveloperMessages; |
| | | 598 | | /// </code> |
| | | 599 | | /// </example> |
| | | 600 | | public IEnumerable<string>? DeveloperMessages |
| | | 601 | | { |
| | | 602 | | get => GetProperty<IEnumerable<string>>(requestException, DeveloperMessagesName); |
| | | 603 | | set => SetProperty(requestException, DeveloperMessagesName, value?.ToArray()); |
| | | 604 | | } |
| | | 605 | | |
| | | 606 | | /// <summary> |
| | | 607 | | /// Converts an <see cref="HttpRequestException"/> into an <see cref="ErrorDetails"/> payload. |
| | | 608 | | /// </summary> |
| | | 609 | | /// <param name="populateErrorInfo"> |
| | | 610 | | /// <see langword="true"/> to include developer-facing details when present; otherwise <see langword="false" |
| | | 611 | | /// </param> |
| | | 612 | | /// <param name="traceId">The trace identifier to expose in the resulting payload.</param> |
| | | 613 | | /// <returns>The structured error payload.</returns> |
| | | 614 | | /// <exception cref="ArgumentNullException">Thrown when <paramref name="requestException"/> is <see langword |
| | | 615 | | /// <example> |
| | | 616 | | /// <code> |
| | | 617 | | /// ErrorDetails details = exception.GetErrorDetails(populateErrorInfo: false, traceId); |
| | | 618 | | /// </code> |
| | | 619 | | /// </example> |
| | | 620 | | public ErrorDetails GetErrorDetails(bool populateErrorInfo = false, string? traceId = null) |
| | | 621 | | { |
| | | 622 | | Ensure.NotNull(requestException); |
| | | 623 | | |
| | | 624 | | return new ErrorDetails |
| | | 625 | | { |
| | | 626 | | Status = requestException.Status, |
| | | 627 | | Title = requestException.Message, |
| | | 628 | | TraceId = traceId ?? Guid.NewGuid().ToString("N"), |
| | | 629 | | Errors = requestException.Errors, |
| | | 630 | | DeveloperMessages = populateErrorInfo ? requestException.DeveloperMessages : null |
| | | 631 | | }; |
| | | 632 | | } |
| | | 633 | | } |
| | | 634 | | } |
| | | 635 | | } |