-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
75 lines (58 loc) · 2.57 KB
/
Program.cs
File metadata and controls
75 lines (58 loc) · 2.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// -------------------------------------------------------
// Copyright (c) BlazorFocused All rights reserved.
// Licensed under the MIT License
// -------------------------------------------------------
using Microsoft.AspNetCore.Mvc;
using MiddlewareSample.Api.Exceptions;
using System.Net;
using BlazorFocused.Exceptions.Middleware;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddOpenApi();
// Register custom exceptions and status codes
builder.Services
// .AddExceptionsMiddleware() -> Use this extension for default correlation key/value and configuration
.AddExceptionsMiddleware(options =>
{
options.CorrelationKey = "X-TestCorrelation-Id";
options.CorrelationKey = CORRELATION_HEADER_KEY;
options.ConfigureCorrelationValue = (httpContext) => httpContext.TraceIdentifier;
options.ConfigureProblemDetails = (httpContext, exception, problemDetails) =>
{
Console.WriteLine("Here you can override the ProblemDetails object returned to the client.");
Console.WriteLine("Also a good place to breakpoint during development to examine thrown exceptions.");
return problemDetails;
};
}) // Use this extension for default correlation key/value
.AddException<RandomException>(HttpStatusCode.FailedDependency);
WebApplication app = builder.Build();
app.UseHttpsRedirection();
app.MapOpenApi();
// Register Exceptions API Middleware
app.UseExceptionsMiddleware();
// Endpoints
app.MapGet("/ThrowRandomException", () =>
{
throw new RandomException();
});
app.MapGet("/ThrowCustomClientException", (
[FromQuery] HttpStatusCode? statusCode,
[FromQuery] string? message,
[FromQuery] string? clientMessage) =>
{
string emptyMessage = "No Message Sent";
CustomClientException exception = (statusCode, message) switch
{
{ statusCode: null, message: null } => new CustomClientException(emptyMessage) { ClientErrorMessage = clientMessage },
{ statusCode: null } => new CustomClientException(message) { ClientErrorMessage = clientMessage },
{ message: null } => new CustomClientException(statusCode.Value, emptyMessage) { ClientErrorMessage = clientMessage },
_ => new CustomClientException(statusCode.Value, message) { ClientErrorMessage = clientMessage }
};
throw exception;
});
app.Run();
// Used for integration test web application factory accessibility
public partial class Program
{
public const string CORRELATION_HEADER_KEY = "Test-Correlation-Id";
}