-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExceptionHandler.cs
More file actions
69 lines (62 loc) · 2.79 KB
/
Copy pathExceptionHandler.cs
File metadata and controls
69 lines (62 loc) · 2.79 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
using FloppyShelf.Problemize.Interfaces;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
namespace FloppyShelf.Problemize.Services;
/// <summary>
/// Exception handler that converts exceptions into standardized problem details responses.
/// </summary>
public sealed class ExceptionHandler : IExceptionHandler
{
private readonly IProblemDetailsService _problemDetailsService;
private readonly IStatusCodeMapper _statusCodeMapper;
/// <summary>
/// Creates a new instance of the <see cref="ExceptionHandler"/> class.
/// </summary>
/// <param name="problemDetailService">The service used to write problem details responses.</param>
/// <param name="statusCodeMapper">The component responsible for mapping exceptions to HTTP status codes.</param>
public ExceptionHandler(IProblemDetailsService problemDetailsService, IStatusCodeMapper statusCodeMapper)
{
_problemDetailsService = problemDetailsService;
_statusCodeMapper = statusCodeMapper;
}
/// <summary>
/// Attempts to handle the exception and generate a problem details response.
/// </summary>
/// <param name="httpContext">The current HTTP context.</param>
/// <param name="exception">The exception to handle.</param>
/// <param name="cancellationToken">Cancellation token for async operations.</param>
/// <returns>True if the exception was handled and a response was written; otherwise, false.</returns>
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
// Set the HTTP response status code based on the exception
httpContext.Response.StatusCode = _statusCodeMapper.GetStatusCode(exception);
var problemDetailsContext = new ProblemDetailsContext
{
HttpContext = httpContext,
Exception = exception,
};
// check for validation exception
if(exception is ValidationException validationException)
{
problemDetailsContext.ProblemDetails = new ValidationProblemDetails
{
Title = "An error occured while validating your request",
Detail = validationException.Message,
Type = validationException.GetType().Name,
};
}
else
{
problemDetailsContext.ProblemDetails = new ProblemDetails
{
Title = "An error occured while processing your request",
Detail = exception.Message,
Type = exception.GetType().Name,
};
}
// Write the problem details response
return await _problemDetailsService.TryWriteAsync(problemDetailsContext);
}
}