Skip to content

Instantly share code, notes, and snippets.

@T-450
Created August 9, 2022 06:24
Show Gist options
  • Select an option

  • Save T-450/ada74ea3e525dd77c22d0876b5eb77f7 to your computer and use it in GitHub Desktop.

Select an option

Save T-450/ada74ea3e525dd77c22d0876b5eb77f7 to your computer and use it in GitHub Desktop.

Revisions

  1. T-450 created this gist Aug 9, 2022.
    60 changes: 60 additions & 0 deletions HttpGlobalExceptionFilter.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,60 @@
    // https://github.com/dotnet-architecture/eShopOnContainers/blob/dev/src/Services/Catalog/Catalog.API/Infrastructure/Filters/HttpGlobalExceptionFilter.cs

    namespace Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure.Filters;

    public class HttpGlobalExceptionFilter : IExceptionFilter
    {
    private readonly IWebHostEnvironment env;
    private readonly ILogger<HttpGlobalExceptionFilter> logger;

    public HttpGlobalExceptionFilter(IWebHostEnvironment env, ILogger<HttpGlobalExceptionFilter> logger)
    {
    this.env = env;
    this.logger = logger;
    }

    public void OnException(ExceptionContext context)
    {
    logger.LogError(new EventId(context.Exception.HResult),
    context.Exception,
    context.Exception.Message);

    if (context.Exception.GetType() == typeof(CatalogDomainException))
    {
    var problemDetails = new ValidationProblemDetails()
    {
    Instance = context.HttpContext.Request.Path,
    Status = StatusCodes.Status400BadRequest,
    Detail = "Please refer to the errors property for additional details."
    };

    problemDetails.Errors.Add("DomainValidations", new string[] { context.Exception.Message.ToString() });

    context.Result = new BadRequestObjectResult(problemDetails);
    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    }
    else
    {
    var json = new JsonErrorResponse
    {
    Messages = new[] { "An error ocurred." }
    };

    if (env.IsDevelopment())
    {
    json.DeveloperMessage = context.Exception;
    }

    context.Result = new InternalServerErrorObjectResult(json);
    context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
    }
    context.ExceptionHandled = true;
    }

    private class JsonErrorResponse
    {
    public string[] Messages { get; set; }

    public object DeveloperMessage { get; set; }
    }
    }