-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: implement global exception handler
- Loading branch information
Showing
4 changed files
with
79 additions
and
76 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
71 changes: 0 additions & 71 deletions
71
src/CrowdParlay.Social.Api/Middlewares/ExceptionHandlingMiddleware.cs
This file was deleted.
Oops, something went wrong.
74 changes: 74 additions & 0 deletions
74
src/CrowdParlay.Social.Api/Services/GlobalExceptionHandler.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
using System.Net; | ||
using System.Net.Mime; | ||
using CrowdParlay.Social.Application.Exceptions; | ||
using Microsoft.AspNetCore.Diagnostics; | ||
using Microsoft.AspNetCore.Mvc; | ||
|
||
namespace CrowdParlay.Social.Api.Services; | ||
|
||
/// <summary> | ||
/// Handles exceptions thrown in the ASP.NET Core pipeline and writes the details to the HTTP response in accordance with RFC 7807. | ||
/// Gets called by the default ASP.NET Core exception handling middleware. | ||
/// </summary> | ||
public class GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger) : IExceptionHandler | ||
{ | ||
public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken cancellationToken) | ||
{ | ||
logger.LogError(exception, "{ExceptionMessage}", exception.Message); | ||
|
||
var problemDetails = exception switch | ||
{ | ||
ValidationException e => ConvertToProblemDetails(e), | ||
FluentValidation.ValidationException e => ConvertToProblemDetails(e), | ||
NotFoundException => GetNotFoundProblemDetails(), | ||
ForbiddenException => GetForbiddenProblemDetails(), | ||
_ => GetDefaultProblemDetails() | ||
}; | ||
|
||
context.Response.ContentType = MediaTypeNames.Application.ProblemJson; | ||
context.Response.StatusCode = problemDetails.Status ?? StatusCodes.Status500InternalServerError; | ||
await context.Response.WriteAsJsonAsync(problemDetails, GlobalSerializerOptions.SnakeCase, cancellationToken); | ||
|
||
return true; | ||
} | ||
|
||
private static ProblemDetails GetDefaultProblemDetails() => new() | ||
{ | ||
Status = (int)HttpStatusCode.InternalServerError, | ||
Detail = "Something went wrong. Try again later.", | ||
}; | ||
|
||
private static ValidationProblemDetails ConvertToProblemDetails(ValidationException exception) => new() | ||
{ | ||
Status = (int)HttpStatusCode.BadRequest, | ||
Detail = "The specified data is invalid.", | ||
Errors = exception.Errors.ToDictionary( | ||
x => x.Key, | ||
x => x.Value.ToArray()) | ||
}; | ||
|
||
private static ValidationProblemDetails ConvertToProblemDetails(FluentValidation.ValidationException exception) => new() | ||
{ | ||
Status = (int)HttpStatusCode.BadRequest, | ||
Detail = "The specified data is invalid.", | ||
Errors = exception.Errors | ||
.GroupBy(failure => failure.PropertyName) | ||
.ToDictionary( | ||
propertyFailureGroup => propertyFailureGroup.Key, | ||
propertyFailureGroup => propertyFailureGroup | ||
.Select(failure => failure.ErrorMessage) | ||
.ToArray()) | ||
}; | ||
|
||
private static ProblemDetails GetNotFoundProblemDetails() => new() | ||
{ | ||
Status = (int)HttpStatusCode.NotFound, | ||
Detail = "The requested resource doesn't exist." | ||
}; | ||
|
||
private static ProblemDetails GetForbiddenProblemDetails() => new() | ||
{ | ||
Status = (int)HttpStatusCode.Forbidden, | ||
Detail = "You have no permission for this action." | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters