-
Notifications
You must be signed in to change notification settings - Fork 2
Middleware usage example
Fedorus edited this page Jul 14, 2021
·
2 revisions
here is default code for global exception handler:
public class GlobalExceptionHandler : IUpdateHandler<BotExampleContext>
{
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}
public async Task HandleAsync(BotExampleContext context, UpdateDelegate<BotExampleContext> next, CancellationToken cancellationToken)
{
try
{
await next(context, cancellationToken);
_logger.LogInformation("Update {0}, no errors", context.Update.Id);
}
catch (Exception e)
{
_logger.LogInformation("Update {0}, has errors {1}", context.Update.Id, e);
}
}
}Constructor parameter will be resolved from DI. And BotExampleContext should be your Context type or generic.
Now lets look at HandleAsync method. As you can see we surround await next(context, cancellationToken); with try-catch construction. That allows us to catch any exception that will happen down the pipe and log it.