From edfd7dc4a8a4f41366e54713bba41b96c8aa938e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20K=C3=BCsters?= Date: Wed, 12 Jun 2024 17:04:20 +0200 Subject: [PATCH] feat: added extension to get HttpStatusCode of a exception --- .../Errors/Extensions/ErrorTypeExtensions.cs | 31 +++++++++++++++++++ .../Extensions/ExceptionExtensions.cs | 26 ++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/Wemogy.Core/Errors/Extensions/ErrorTypeExtensions.cs create mode 100644 src/Wemogy.Core/Extensions/ExceptionExtensions.cs diff --git a/src/Wemogy.Core/Errors/Extensions/ErrorTypeExtensions.cs b/src/Wemogy.Core/Errors/Extensions/ErrorTypeExtensions.cs new file mode 100644 index 0000000..fbc3fe7 --- /dev/null +++ b/src/Wemogy.Core/Errors/Extensions/ErrorTypeExtensions.cs @@ -0,0 +1,31 @@ +using System.Net; +using Wemogy.Core.Errors.Enums; + +namespace Wemogy.Core.Errors.Extensions +{ + public static class ErrorTypeExtensions + { + public static HttpStatusCode ToHttpStatusCode(this ErrorType errorType) + { + switch (errorType) + { + case ErrorType.Authorization: + return HttpStatusCode.Forbidden; + case ErrorType.Conflict: + return HttpStatusCode.Conflict; + case ErrorType.Failure: + return HttpStatusCode.BadRequest; + case ErrorType.NotFound: + return HttpStatusCode.NotFound; + case ErrorType.PreconditionFailed: + return HttpStatusCode.PreconditionFailed; + case ErrorType.Unexpected: + return HttpStatusCode.InternalServerError; + case ErrorType.Validation: + return HttpStatusCode.BadRequest; + default: + return HttpStatusCode.InternalServerError; + } + } + } +} diff --git a/src/Wemogy.Core/Extensions/ExceptionExtensions.cs b/src/Wemogy.Core/Extensions/ExceptionExtensions.cs new file mode 100644 index 0000000..8b06c90 --- /dev/null +++ b/src/Wemogy.Core/Extensions/ExceptionExtensions.cs @@ -0,0 +1,26 @@ +using System; +using System.Net; +using FluentValidation; +using Wemogy.Core.Errors.Exceptions; +using Wemogy.Core.Errors.Extensions; + +namespace Wemogy.Core.Extensions +{ + public static class ExceptionExtensions + { + public static HttpStatusCode GetHttpStatusCode(this Exception exception) + { + if (exception is ErrorException errorException) + { + return errorException.ErrorType.ToHttpStatusCode(); + } + + if (exception is ValidationException) + { + return HttpStatusCode.BadRequest; + } + + return HttpStatusCode.InternalServerError; + } + } +}