79529143

Date: 2025-03-23 14:59:35
Score: 0.5
Natty:
Report link

I’ve carefully reviewed both of your questions. If I understand your issue correctly, you’re looking to implement a custom middleware that uses a ProblemDetails object. This global middleware would handle all exceptions, and then adjust the response status code based on the type of exception encountered.

This implementation could help:

public class GlobalErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;

    public GlobalErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context); // Call the next middleware in the pipeline
        }
        catch (Exception ex)
        {
            // Handle exceptions and return a ProblemDetails response
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        // Determine the status code based on the exception type
        var statusCode = HttpStatusCode.InternalServerError; // Default status code

        if (exception is ArgumentNullException)
        {
            statusCode = HttpStatusCode.BadRequest; // 400
        }
        if (exception is FileNotFoundException)
        {
            statusCode = HttpStatusCode.NotFound; // 404
        }
        // Add more custom exception handling as needed

        // Create a ProblemDetails object
        var problemDetails = new ProblemDetails
        {
            Type = "https://tools.ietf.org/html/rfc7231#section-6.6.1", // Link to error documentation
            Title = "An error occurred while processing your request.",
            Status = (int)statusCode,
            Detail = exception.Message,
            Instance = context.Request.Path
        };

        // Set the response content type and status code
        context.Response.ContentType = "application/problem+json";
        context.Response.StatusCode = (int)statusCode;

        // Serialize the ProblemDetails object to JSON and write it to the response
        return context.Response.WriteAsJsonAsync(problemDetails);
    }
}

The exceptions must be THROWN in your code somewhere in your BLL better:

    [HttpGet]
    [Route(nameof(FileExists))]
    public async Task<bool> FileExists([FromQuery] string fileName, [FromQuery] Guid? containerId)
    {
        if (fileName is null)
            throw new ArgumentNullException();

        bool file = await IsFileExists();

        if (file == false)
            throw new FileNotFoundException();

        return file;
    }
 

Testing Using POSTMAN:

Status Code: 400 Bad Request

enter image description here

Status Code: 404 Not Found

enter image description here

Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: rouisaek