JSON-customized errors

The customization and serialization of the exceptions is a helpful way to simplify error handling and improve the monitoring of the web service. These techniques are sometimes necessary for communicating exceptions to a client so that errors can be handled and managed. In general, while the HTTP status code provides summary information about the status of the request, the content of the response provides more detailed information about the error.

It is possible to extend the error handling behavior using filters. First of all, let's create a new standard model that represents an error result:

namespace Catalog.API.Exceptions
{
public class JsonErrorPayload
{
public int EventId { get; set; }
public object DetailedMessage { get; set; }
}
}

The preceding class is under the Filters folder structure. It contains an EventId attribute and a DetailedMessage of an object typeSecondly, we should continue by implementing a new filter that extends the IExceptionFilter interface. The filter will be triggered when an exception is raised, and it will modify the content of the response returned to the client:

using System.Net;
using Catalog.API.Exceptions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Catalog.API.Filters
{
public class JsonExceptionAttribute : TypeFilterAttribute
{
public JsonExceptionAttribute() : base(typeof(HttpCustomExceptionFilterImpl))
{
}

private class HttpCustomExceptionFilterImpl : IExceptionFilter
{
private readonly IWebHostEnvironment _env;
private readonly ILogger<HttpCustomExceptionFilterImpl> _logger;

public HttpCustomExceptionFilterImpl(IWebHostEnvironment env,
ILogger<HttpCustomExceptionFilterImpl> logger)
{
_env = env;
_logger = logger;
}

public void OnException(ExceptionContext context)
{
var eventId = new EventId(context.Exception.HResult);

_logger.LogError(eventId,
context.Exception,
context.Exception.Message);

var json = new JsonErrorPayload { EventId = eventId.Id };

if (_env.IsDevelopment())
{
json.DetailedMessage = context.Exception;
}

var exceptionObject = new ObjectResult(json) { StatusCode = 500 };

context.Result = exceptionObject;
context.HttpContext.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
}
}

The preceding code implements the IExceptionFilter interface. The class contains the definition of the constructor used to inject some of the dependencies of the filter. It also contains the OnException method, which initializes a new JsonErrorPayload object populated with the eventId field and the content of the message contained in the exception. Depending on the environment, take a look at the IsDevelopment() check; it also populates the resulting exception object with a detailed error message. Finally, the OnException method uses the HttpContext, defined as a parameter, to set the HttpStatusCode.InternalServerError, and to add exceptionObject previously created as a result of the execution. This approach guarantees to handle exception in a unique way, by centralizing the serialization and the resulting message format of all the errors returned by the web service.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.111.85