microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
core/samples/PABot/AdapterWithErrorHandler.cs
65lines · modecode
| 1 | // Copyright (c) Microsoft Corporation. |
| 2 | // Licensed under the MIT License. |
| 3 | |
| 4 | using Microsoft.Bot.Builder; |
| 5 | using Microsoft.Bot.Builder.Integration.AspNet.Core; |
| 6 | using Microsoft.Bot.Builder.Teams; |
| 7 | using Microsoft.Bot.Builder.TraceExtensions; |
| 8 | using Microsoft.Teams.Bot.Apps; |
| 9 | using Microsoft.Teams.Bot.Compat; |
| 10 | |
| 11 | namespace PABot |
| 12 | { |
| 13 | public class AdapterWithErrorHandler : CompatAdapter |
| 14 | { |
| 15 | public AdapterWithErrorHandler( |
| 16 | TeamsBotApplication teamsBotApp, |
| 17 | IHttpContextAccessor httpContextAccessor, |
| 18 | IConfiguration configuration, |
| 19 | ILogger<IBotFrameworkHttpAdapter> logger, |
| 20 | IStorage storage, |
| 21 | ConversationState conversationState |
| 22 | ) |
| 23 | : base( |
| 24 | teamsBotApp, |
| 25 | httpContextAccessor, |
| 26 | logger) |
| 27 | { |
| 28 | base.Use(new TeamsSSOTokenExchangeMiddleware(storage, configuration["ConnectionName"] ?? "graph")); |
| 29 | |
| 30 | OnTurnError = async (turnContext, exception) => |
| 31 | { |
| 32 | // Log any leaked exception from the application. |
| 33 | // NOTE: In production environment, you should consider logging this to |
| 34 | // Azure Application Insights. Visit https://aka.ms/bottelemetry to see how |
| 35 | // to add telemetry capture to your bot. |
| 36 | logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}"); |
| 37 | |
| 38 | // Uncomment below commented line for local debugging.. |
| 39 | // await turnContext.SendActivityAsync($"Sorry, it looks like something went wrong. Exception Caught: {exception.Message}"); |
| 40 | |
| 41 | if (conversationState != null) |
| 42 | { |
| 43 | try |
| 44 | { |
| 45 | // Delete the conversationState for the current conversation to prevent the |
| 46 | // bot from getting stuck in a error-loop caused by being in a bad state. |
| 47 | // ConversationState should be thought of as similar to "cookie-state" in a Web pages. |
| 48 | await conversationState.DeleteAsync(turnContext); |
| 49 | } |
| 50 | catch (Exception e) |
| 51 | { |
| 52 | logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}"); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // Send a trace activity, which will be displayed in the Bot Framework Emulator |
| 57 | await turnContext.TraceActivityAsync( |
| 58 | "OnTurnError Trace", |
| 59 | exception.Message, |
| 60 | "https://www.botframework.com/schemas/error", |
| 61 | "TurnError"); |
| 62 | }; |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |