-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGlobalExceptionHandler.cs
More file actions
37 lines (32 loc) · 1.1 KB
/
GlobalExceptionHandler.cs
File metadata and controls
37 lines (32 loc) · 1.1 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
using Microsoft.AspNetCore.Diagnostics;
namespace Evently.Server.Common.Middlewares;
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler {
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken) {
string exceptionMessage = exception.Message;
logger.LogError(
"Error Message: {exceptionMessage}, Time of occurrence {time}",
exceptionMessage,
DateTime.UtcNow);
switch (exception) {
case ArgumentException:
httpContext.Response.StatusCode = 400;
await httpContext.Response.WriteAsJsonAsync(value: new {
Title = "Validation Error",
Detail = exceptionMessage,
Status = StatusCodes.Status400BadRequest,
},
cancellationToken);
break;
default:
httpContext.Response.StatusCode = 500;
await httpContext.Response.WriteAsJsonAsync(value: new {
Title = "Server Error",
Detail = "An unexpected error occurred.",
Status = StatusCodes.Status500InternalServerError,
},
cancellationToken);
break;
}
return true;
}
}