From f18683faa95704c73ee6c3ad0cc9aa26cdf07485 Mon Sep 17 00:00:00 2001 From: Pham Tien Dung Date: Wed, 4 Sep 2024 15:31:01 +0700 Subject: [PATCH] Add NotFoundException handling and refactor CustomProblemDetails Reordered using directives in ExceptionMiddleware.cs and added a new directive for MLS.Application.Exceptions. Added a new case for handling NotFoundException in ExceptionMiddleware class, setting statusCode to HttpStatusCode.NotFound and creating a CustomProblemDetails object. Added a default case to handle other exceptions, setting problem details accordingly. Refactored CustomProblemDetails class in CustomProblemDetails.cs, moving class definition outside of the nested block and retaining the Errors property. --- src/MLS.Api/Middleware/ExceptionMiddleware.cs | 6 ++++-- src/MLS.Api/Models/CustomProblemDetails.cs | 11 +++++------ 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/MLS.Api/Middleware/ExceptionMiddleware.cs b/src/MLS.Api/Middleware/ExceptionMiddleware.cs index dc4c3be..bcc57cd 100644 --- a/src/MLS.Api/Middleware/ExceptionMiddleware.cs +++ b/src/MLS.Api/Middleware/ExceptionMiddleware.cs @@ -1,6 +1,6 @@ -using System.Net; -using MLS.Api.Models; +using MLS.Api.Models; using MLS.Application.Exceptions; +using System.Net; namespace MLS.Api.Middleware; @@ -43,6 +43,7 @@ private async Task HandleExceptionAsync(HttpContext httpContext, Exception ex) Errors = badRequestException.ValidationErrors }; break; + case NotFoundException notFound: statusCode = HttpStatusCode.NotFound; problem = new CustomProblemDetails @@ -53,6 +54,7 @@ private async Task HandleExceptionAsync(HttpContext httpContext, Exception ex) Detail = notFound.InnerException?.Message }; break; + default: problem = new CustomProblemDetails { diff --git a/src/MLS.Api/Models/CustomProblemDetails.cs b/src/MLS.Api/Models/CustomProblemDetails.cs index 813217e..0c92d3e 100644 --- a/src/MLS.Api/Models/CustomProblemDetails.cs +++ b/src/MLS.Api/Models/CustomProblemDetails.cs @@ -1,9 +1,8 @@ using Microsoft.AspNetCore.Mvc; -namespace MLS.Api.Models +namespace MLS.Api.Models; + +public class CustomProblemDetails : ProblemDetails { - public class CustomProblemDetails : ProblemDetails - { - public IDictionary Errors { get; set; } = new Dictionary(); - } -} + public IDictionary Errors { get; set; } = new Dictionary(); +} \ No newline at end of file