File size: 2,406 Bytes
63208c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System.Net;
using System.Text.Json;
using Tawasol.Domain.Exceptions;
using Tawasol.Application.Common.Models;
using Tawasol.Application.Common.Exceptions;

namespace Tawasol.API.Middleware;

public class ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "An unhandled exception occurred.");
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var code = HttpStatusCode.InternalServerError;
        Result? result = null;

        switch (exception)
        {
            case ValidationException validationException:
                code = HttpStatusCode.BadRequest;
                // Format errors as a list of "Property: Message" for simplicity or return the dictionary directly.
                // For Flutter UI, we'll flatten the dictionary to a list of error strings for the Errors property.
                var flattenedErrors = validationException.Errors
                    .SelectMany(kvp => kvp.Value.Select(msg => $"{kvp.Key}: {msg}"))
                    .ToList();
                result = Result.Failure(flattenedErrors, "فشل التحقق من البيانات");
                break;
            case NotFoundException notFoundException:
                code = HttpStatusCode.NotFound;
                result = Result.Failure(notFoundException.Message, "العنصر غير موجود");
                break;
            case DomainException domainException:
                code = HttpStatusCode.BadRequest;
                result = Result.Failure(domainException.Message, "خطأ في منطق الأعمال");
                break;
            default:
                result = Result.Failure("حدث خطأ داخلي في الخادم", "فشلت العملية");
                break;
        }

        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;

        var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
        return context.Response.WriteAsync(JsonSerializer.Serialize(result, options));
    }
}