Home > Back-end >  ASP.NET Core 6 Web API - returns all errors as JSON
ASP.NET Core 6 Web API - returns all errors as JSON

Time:02-19

ASP.NET Core returns (if error) only HTTP status code and empty body. Is it possible to handle all errors?

I would like return HTTP status code and json? For example

{
    "status": STATUS_CODE,
    "message": "error"
}

CodePudding user response:

You can use filters for this. Create a filter similar to this:

 public class HandledResultFilter : ExceptionFilterAttribute
{
    public override void OnException(ExceptionContext context)
    {
        context.ExceptionHandled = true;
        var error = new HandledResult<Exception>(context.Exception).HandleException();

        context.HttpContext.Response.Clear();
        context.HttpContext.Response.ContentType = new MediaTypeHeaderValue("application/json").ToString();
        context.HttpContext.Response.StatusCode = error.StatusCode;
        context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(error), Encoding.UTF8);
    }
}

And register it:

services.AddMvc(mvcOptions =>
            {
                mvcOptions.Filters.Add(new HandledResultFilter());
            });

CodePudding user response:

You can create your own middleware to handle any errors and return to the client any information you want.

You can place the middleware in the Startup. Configure method before any other middleware and before controller endpoint mappings to handle every error.

Details are in this article: Error Handler Tutorial for ASP NET

  • Related