File tree 4 files changed +44
-43
lines changed
4 files changed +44
-43
lines changed Original file line number Diff line number Diff line change @@ -10,7 +10,7 @@ namespace JixMinApi.Features.Todo;
10
10
11
11
public static class TodoEndpoints
12
12
{
13
- public static void InjectTodoEndpointServices ( this IServiceCollection services )
13
+ public static void AddTodoEndpointServices ( this IServiceCollection services )
14
14
{
15
15
services . AddDbContext < TodoDb > ( opt => opt . UseInMemoryDatabase ( Constants . TodoApiGroupName ) ) ;
16
16
}
Original file line number Diff line number Diff line change 1
1
using JixMinApi . Features . Todo ;
2
+ using JixMinApi . Shared ;
2
3
using Microsoft . OpenApi . Models ;
3
4
using System . Reflection ;
4
5
23
24
builder . Services . AddMediatR ( cfg => cfg . RegisterServicesFromAssembly ( typeof ( Program ) . Assembly ) ) ;
24
25
25
26
// Inject endpoint services
26
- builder . Services . InjectTodoEndpointServices ( ) ;
27
+ builder . Services . AddTodoEndpointServices ( ) ;
28
+
29
+ builder . Services . AddExceptionHandler < GlobalExceptionHandler > ( ) ;
30
+ builder . Services . AddProblemDetails ( ) ;
27
31
28
32
var app = builder . Build ( ) ;
29
33
30
34
// Configure the HTTP request pipeline.
35
+ app . UseExceptionHandler ( ) ;
36
+
31
37
if ( app . Environment . IsDevelopment ( ) )
32
38
{
33
39
app . UseSwagger ( ) ;
Original file line number Diff line number Diff line change
1
+ using Microsoft . AspNetCore . Diagnostics ;
2
+ using Microsoft . AspNetCore . Mvc ;
3
+
4
+ namespace JixMinApi . Shared ;
5
+
6
+ internal sealed class GlobalExceptionHandler : IExceptionHandler
7
+ {
8
+ private readonly ILogger < GlobalExceptionHandler > _logger ;
9
+
10
+ public GlobalExceptionHandler ( ILogger < GlobalExceptionHandler > logger )
11
+ {
12
+ _logger = logger ;
13
+ }
14
+
15
+ public async ValueTask < bool > TryHandleAsync (
16
+ HttpContext httpContext ,
17
+ Exception exception ,
18
+ CancellationToken cancellationToken )
19
+ {
20
+ _logger . LogError (
21
+ exception , "Exception occurred: {Message}" , exception . Message ) ;
22
+
23
+ var problemDetails = new ProblemDetails
24
+ {
25
+ Status = StatusCodes . Status500InternalServerError ,
26
+ Title = "Server error"
27
+ } ;
28
+
29
+ httpContext . Response . StatusCode = problemDetails . Status . Value ;
30
+
31
+ await httpContext . Response
32
+ . WriteAsJsonAsync ( problemDetails , cancellationToken ) ;
33
+
34
+ return true ;
35
+ }
36
+ }
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments