IExceptionHandler

noun

say it: “EYE ek-SEP-shun HAND-ler” /aɪ ɪkˈsɛpʃən ˈhændlər/

An ASP.NET Core interface for a class that turns chosen unhandled exceptions into responses for the whole app.

What is IExceptionHandler in ASP.NET Core?

IExceptionHandler — An interface for a class that ASP.NET Core calls when an exception goes unhandled anywhere in the app. It returns true when it wrote a response for that exception, or false to let the next handler, or the default error response, deal with it.

class OutOfStockHandler : IExceptionHandler
{
    public async ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken token)
    {
        if (exception is not OutOfStockException) return false;
        context.Response.StatusCode = StatusCodes.Status409Conflict;
        await context.Response.WriteAsJsonAsync(new { error = exception.Message }, token);
        return true;
    }
}

In a sentence

  • “Our IExceptionHandler turns OutOfStockException into a 409 everywhere in the API.”

Level: Freelancer · More ASP.NET Core terms at this level

Updated