Buscar contenidos

miércoles, 27 de junio de 2018

NetCore Global Error Catcher

https://stackoverflow.com/questions/48578065/global-error-catcher



You could create your own Exception filter, which implements IExceptionFilter e.g.:
public class GlobalExceptionFilter : IExceptionFilter
{
    ILogger<GlobalExceptionFilter> logger = null;

    public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> exceptionLogger)
    {
        logger = exceptionLogger;
    }

    public void OnException(ExceptionContext context)
    {
        // log the exception
        logger.LogError(0, context.Exception.GetBaseException(), "Exception occurred.");
    }
}
You can then add this filter in your ConfigureServices method as follows:
services.AddMvc(o => { o.Filters.Add<GlobalExceptionFilter>(); });
This will catch any unhanded exceptions that occur as the result of a request. For 404s you can add the following to your Configure method:
app.UseStatusCodePagesWithReExecute("/error/{0}");
You can then log the status code in your ErrorController.

No hay comentarios:

Publicar un comentario