public AdapterWithErrorHandler( ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, IMiddlewareInjector middlewareInjector, ConversationState conversationState = null) : base(credentialProvider) { OnTurnError = async(turnContext, exception) => { logger.LogError($"Exception caught: {exception.Message}"); await turnContext.SendActivityAsync("Sorry, its looks like somethong went wrong."); if (conversationState != null) { try { await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; middlewareInjector.Inject(this); }
/// <summary> /// Initializes a new instance of the <see cref="AdapterWithErrorHandler"/> class. /// </summary> /// <param name="configuration">configuration.</param> /// <param name="telemetryClient">telemetry client.</param> /// <param name="conversationState">conversation state.</param> public AdapterWithErrorHandler(IConfiguration configuration, TelemetryClient telemetryClient, ConversationState conversationState = null) : base(configuration) { this.OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. telemetryClient.TrackException(exception); // Send a catch-all apology to the user. var errorMessage = MessageFactory.Text(Strings.ErrorMsgText, Strings.ErrorMsgText, InputHints.ExpectingInput); await turnContext.SendActivityAsync(errorMessage); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { telemetryClient.TrackException(e); } } }; }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(configuration, logger) { OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. var errorMessage = MessageFactory.Text(ErrorMsgText, ErrorMsgText, InputHints.ExpectingInput); await turnContext.SendActivityAsync(errorMessage); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(credentialProvider) { OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all appology to the user. await turnContext.SendActivityAsync("Sorry, it looks like something went wrong."); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
public AdapterFrameworkHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, BotStateService botService, ConversationState conversationState = null) : base(configuration, logger) { _logger = logger; _botService = botService; //This method is triggered when an exception is thrown somewhere within a Dialog. OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message} {JsonConvert.SerializeObject(exception)}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync(ChannelFormattingService.FormatSimpleMessage(turnContext, "Sorry, it looks like something went wrong. Please refresh the page and try again.")); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(credentialProvider) { OnTurnError = async(turnContext, exception) => { // Registre qualquer exceção perdida do aplicativo. logger.LogError($"Exceção capturada: {exception.Message}"); // Envie um pedido de desculpas para o usuário. await turnContext.SendActivityAsync("Desculpe, parece que algo deu errado."); if (conversationState != null) { try { // Exclua o conversationState da conversa atual para impedir que o // bot de ficar preso em um loop de erro causado por estar em um estado ruim. // ConversationState deve ser considerado como semelhante a "cookie-state" em páginas da Web. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exceção detectada ao tentar excluir o ConversationState: {e.Message}"); } } }; }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, ShowTypingMiddleware showTypingMiddleware, ConversationState conversationState = null) : base(configuration, logger) { Use(showTypingMiddleware); OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}"); // Send a message to the user await SendWithoutMiddleware(turnContext, "Sorry, Could you please try another statement."); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } // Send a trace activity, which will be displayed in the Bot Framework Emulator await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError"); }; }
public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, IStorage storage, UserState userState, ConversationState conversationState, IConfiguration configuration) : base(credentialProvider) { this.UseStorage(storage); this.UseBotState(userState); this.UseBotState(conversationState); string[] paths = { ".", $"{nameof(AdapterWithErrorHandler)}.lg" }; string fullPath = Path.Combine(paths); _templates = Templates.ParseFile(fullPath); OnTurnError = async(turnContext, exception) => { logger.LogError($"Exception caught : {exception.Message}"); await turnContext.SendActivityAsync(ActivityFactory.FromObject(_templates.Evaluate("SomethingWentWrong", exception))); if (conversationState != null) { try { await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(configuration, logger) { OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. // NOTE: In production environment, you should consider logging this to // Azure Application Insights. Visit https://aka.ms/bottelemetry to see how // to add telemetry capture to your bot. logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}"); // Send a message to the user await turnContext.SendActivityAsync("The bot encountered an error or bug."); await turnContext.SendActivityAsync("To continue to run this bot, please fix the bot source code."); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } // Send a trace activity, which will be displayed in the Bot Framework Emulator await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError"); }; }
public WeChatAdapterWithErrorHandler(WeChatSettings settings, IStorage storage, IBackgroundTaskQueue taskQueue, ILogger logger = null, ConversationState conversationState = null, UserState userState = null) : base(settings, storage, taskQueue, logger) { OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync("Sorry, it looks like something went wrong."); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; this.Use(new AutoSaveStateMiddleware(conversationState, userState)); }
public async Task TestConversationResetOnException() { var storage = new MemoryStorage(); var userState = new UserState(storage); var conversationState = new ConversationState(storage); var adapter = new TestAdapter() .UseStorage(storage) .UseState(userState, conversationState); adapter.OnTurnError = async(context, exception) => { await conversationState.DeleteAsync(context); await context.SendActivityAsync(exception.Message); }; var dm = new DialogManager(new TestDialog()); await new TestFlow((TestAdapter)adapter, (turnContext, cancellationToken) => { return(dm.OnTurnAsync(turnContext, cancellationToken: cancellationToken)); }) .Send("yo") .AssertReply("unknown") .Send("yo") .AssertReply("havedata") .Send("throw") .AssertReply("throwing") .Send("yo") .AssertReply("unknown") .Send("yo") .AssertReply("havedata") .StartTestAsync(); }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(configuration, logger) { OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}{Environment.NewLine}{exception.StackTrace}"); // Send a message to the user var errorMessageText = $"Unhandled error: {exception.Message}"; var errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput); await turnContext.SendActivityAsync(errorMessage); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } // Send a trace activity, which will be displayed in the Bot Framework Emulator await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError"); }; }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, TemplateManager templateManager, TelemetryInitializerMiddleware telemetryInitializerMiddleware, ConversationState conversationState = null, UserState userState = null) : base(configuration, logger) { OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. var errorMessage = templateManager.GenerateActivity("ErrorMessage"); await turnContext.SendActivityAsync(errorMessage); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; Use(telemetryInitializerMiddleware); Use(new AutoSaveStateMiddleware(conversationState, userState)); }
/// <summary> /// Initializes a new instance of the <see cref="LearnNowAdapterWithErrorHandler"/> class. /// </summary> /// <param name="configuration">Application configurations.</param> /// <param name="logger">Instance to send logs to the Application Insights service.</param> /// <param name="localizer">The current cultures' string localizer.</param> /// <param name="conversationState">Conversation state.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> public LearnNowAdapterWithErrorHandler( IConfiguration configuration, ILogger <IBotFrameworkHttpAdapter> logger, IStringLocalizer <Strings> localizer, ConversationState conversationState = null, CancellationToken cancellationToken = default) : base(configuration) { this.OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError(exception, $"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync(localizer.GetString("ErrorMessage"), cancellationToken : cancellationToken); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception ex) { logger.LogError(ex, $"Exception caught on attempting to Delete ConversationState : {ex.Message}"); throw; } } }; }
public AdapterWithErrorHandler(ICredentialProvider credentialProvider, ILogger <BotFrameworkHttpAdapter> logger, ActiveConversationsStore activeConversationsStore, ConversationState conversationState = null) : base(credentialProvider) { _activeConversationsStore = activeConversationsStore; OnTurnError = async(turnContext, exception) => { logger.LogError($"Exception caught : {exception.Message}"); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); var conversationId = turnContext.Activity.GetConversationReference().Conversation.Id; await _activeConversationsStore.RemoveConversationOnError(conversationId); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
/// <summary> /// Processes a message activity. /// </summary> /// <param name="turnContext">Context for the current turn of conversation.</param> /// <param name="cancellationToken">CancellationToken propagates notifications that operations should be cancelled.</param> /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns> protected override async Task OnMessageActivityAsync(ITurnContext <IMessageActivity> turnContext, CancellationToken cancellationToken) { if (_skillsConfig.Skills.ContainsKey(turnContext.Activity.Text)) { var deliveryMode = await _deliveryModeProperty.GetAsync(turnContext, () => null, cancellationToken); var selectedSkill = _skillsConfig.Skills[turnContext.Activity.Text]; var v3Bots = new List <string> { "EchoSkillBotDotNetV3", "EchoSkillBotJSV3" }; if (selectedSkill != null && deliveryMode == DeliveryModes.ExpectReplies && v3Bots.Contains(selectedSkill.Id)) { var message = MessageFactory.Text("V3 Bots do not support 'expectReplies' delivery mode."); await turnContext.SendActivityAsync(message, cancellationToken); // Forget delivery mode and skill invocation. await _deliveryModeProperty.DeleteAsync(turnContext, cancellationToken); await _activeSkillProperty.DeleteAsync(turnContext, cancellationToken); // Restart setup dialog await _conversationState.DeleteAsync(turnContext, cancellationToken); } } await _dialog.RunAsync(turnContext, _dialogStateProperty, cancellationToken); }
public TestBotHttpAdapter( ICredentialProvider credentialProvider, IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, IStorage storage, UserState userState, ConversationState conversationState, ResourceExplorer resourceExplorer) : base(configuration, credentialProvider) { this.UseStorage(storage); this.UseState(userState, conversationState); var registrations = new TypeRegistration[] { new TypeRegistration <MultiplyDialog>("Testbot.Multiply"), new TypeRegistration <JavascriptAction>("Testbot.JavascriptAction") }; this.UseResourceExplorer(resourceExplorer, registrations); this.UseAdaptiveDialogs(); this.UseQnAMaker(); this.UseLanguageGeneration(resourceExplorer); this.Use(new RegisterClassMiddleware <IConfiguration>(configuration)); // this.UseDebugger(configuration.GetValue<int>("debugport", 4712), events: new Events<AdaptiveEvents>()); this.OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync("Sorry, it looks like something went wrong."); await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext).ConfigureAwait(false); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
/// <summary> /// Deletes the conversationState for the current conversation to prevent the bot from getting stuck in an error-loop caused by being in a bad state. /// ConversationState should be thought of as similar to "cookie-state" in a Web pages. /// </summary> /// <param name="turnContext">Context for the current turn of conversation.</param> /// <param name="cancellationToken">CancellationToken propagates notifications that operations should be cancelled.</param> /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns> private async Task ClearConversationStateAsync(ITurnContext turnContext, CancellationToken cancellationToken) { if (_conversationState != null) { try { await _conversationState.DeleteAsync(turnContext, cancellationToken); } catch (Exception ex) { _logger.LogError(ex, $"Exception caught on attempting to Delete ConversationState : {ex}"); } } }
private async Task ClearConversationStateAsync(ITurnContext turnContext) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" for a Web page. await _conversationState.DeleteAsync(turnContext); } catch (Exception ex) { _logger.LogError(ex, $"Exception caught on attempting to Delete ConversationState : {ex}"); } }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, Translator translatorMiddleware, VoiceMiddleware voiceMiddleware, ConversationState conversationState = null) : base(configuration, logger) { if (translatorMiddleware != null) { // Add translator middleware to the adapter's middleware pipeline Use(translatorMiddleware); } if (voiceMiddleware == null) { throw new NullReferenceException(nameof(voiceMiddleware)); } // Add voice middleware to the adapter's middleware pipeline Use(voiceMiddleware); OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}"); // Send a message to the user var errorMessageText = "The bot encountered an error or bug."; var errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput); await turnContext.SendActivityAsync(errorMessage); errorMessageText = "To continue to run this bot, please fix the bot source code."; errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput); await turnContext.SendActivityAsync(errorMessage); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } // Send a trace activity, which will be displayed in the Bot Framework Emulator await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError"); }; }
/// <summary> /// Initializes a new instance of the <see cref="CoreBotAdapter"/> class. /// </summary> /// <param name="configuration">Application configuration.</param> /// <param name="credentialProvider">Credential provider.</param> /// <param name="authenticationConfiguration">Authentication configuration for the adapter.</param> /// <param name="channelProvider">Channel provider for the adapter.</param> /// <param name="storage">Registered storage for the adapter.</param> /// <param name="conversationState">Conversation state for the adapter.</param> /// <param name="userState">User state for the adapter.</param> /// <param name="middlewares">Collection of registered middlewares to be used in the adapter.</param> /// <param name="logger">Telemetry logger.</param> public CoreBotAdapter( IConfiguration configuration, ICredentialProvider credentialProvider, AuthenticationConfiguration authenticationConfiguration, IChannelProvider channelProvider, IStorage storage, ConversationState conversationState, UserState userState, IEnumerable <IMiddleware> middlewares, ILogger <BotFrameworkHttpAdapter> logger) : base(credentialProvider, authenticationConfiguration, channelProvider, logger: logger) { this.UseStorage(storage) .UseBotState(userState, conversationState) .Use(new RegisterClassMiddleware <IConfiguration>(configuration)); // Pick up feature based middlewares such as telemetry or transcripts foreach (IMiddleware middleware in middlewares) { this.Use(middleware); } OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application Logger.LogError(exception, exception.Message); try { // Send the exception message to the user. Since the default behavior does not // send logs or trace activities, the bot appears hanging without any activity // to the user. await turnContext.SendActivityAsync(exception.Message).ConfigureAwait(false); if (conversationState != null) { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. await conversationState.DeleteAsync(turnContext).ConfigureAwait(false); } } #pragma warning disable CA1031 // Do not catch general exception types (we just log the exception and continue) catch (Exception ex) #pragma warning restore CA1031 // Do not catch general exception types { Logger.LogError(ex, $"Exception caught on attempting to Delete ConversationState : {ex.Message}"); } }; }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(configuration, logger) { OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}"); // Send a message to the user var errorMessageText = exception.Message; //"The bot encounted an error or bug."; var errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput); await turnContext.SendActivityAsync(errorMessage); errorMessageText = "To continue to run this bot, please contact RPA Support."; errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput); errorMessage.SuggestedActions = new SuggestedActions() { Actions = new List <CardAction>() { new CardAction() { Title = "To contact RPA support click here", Text = "To contact RPA support click here", Type = ActionTypes.PostBack, Value = "*****@*****.**", DisplayText = "openEmail" } }, }; await turnContext.SendActivityAsync(errorMessage); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } // Send a trace activity, which will be displayed in the Bot Framework Emulator await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError"); }; }
/// <summary> /// Initializes a new instance of the <see cref="EmployeeTrainingAdapterWithErrorHandler"/> class. /// </summary> /// <param name="configuration">Application configurations.</param> /// <param name="logger">Instance to send logs to the Application Insights service.</param> /// <param name="employeeTrainingActivityMiddleware">Represents middle ware that can operate on incoming activities.</param> /// <param name="localizer">The current cultures' string localizer.</param> /// <param name="conversationState">Conversation state.</param> /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param> public EmployeeTrainingAdapterWithErrorHandler( IConfiguration configuration, ILogger <IBotFrameworkHttpAdapter> logger, EmployeeTrainingActivityMiddleware employeeTrainingActivityMiddleware, IStringLocalizer <Strings> localizer, ConversationState conversationState = null, CancellationToken cancellationToken = default) : base(configuration) { if (employeeTrainingActivityMiddleware == null) { throw new NullReferenceException(nameof(EmployeeTrainingActivityMiddleware)); } // Add activity middle ware to the adapter's middle ware pipeline this.Use(employeeTrainingActivityMiddleware); this.OnTurnError = async(turnContext, exception) => { var error = exception as ErrorResponseException; // Log any leaked exception from the application. logger.LogError(exception, $"Exception caught : {exception.Message}"); // If Http error 'TooManyRequests' arises due to background service notification, do not send generic error message to user. if (error.Response.StatusCode != HttpStatusCode.TooManyRequests) { // Send a catch-all apology to the user. await turnContext.SendActivityAsync(localizer.GetString("ErrorMessage"), cancellationToken : cancellationToken); } if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception ex) { logger.LogError(ex, $"Exception caught on attempting to Delete ConversationState : {ex.Message}"); throw; } } }; }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, IStorage storage, UserState userState, ConversationState conversationState = null) : base(configuration, logger) { this.UseStorage(storage); this.UseState(userState, conversationState); OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}"); // Send a message to the user await turnContext.SendActivityAsync("Sorry! An error has occurred."); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError(e, $"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } var debug_messages = bool.TryParse(configuration["crm:debug_messages"], out var msg_debug) && msg_debug; var debug_errors = bool.TryParse(configuration["crm:debug_errors"], out var err_debug) && err_debug; if (debug_messages || debug_errors) { //if (turnContext.Activity.ChannelId == "emulator") if (exception is Microsoft.Bot.Schema.ErrorResponseException erex) { await turnContext.SendActivityAsync($"Error Reponse\r\n{erex.Request.Content}\r\n{erex.Message}\r\n{JsonConvert.SerializeObject(erex.Body)}\r\n{JsonConvert.SerializeObject(erex.Data)}"); } else { await turnContext.SendActivityAsync($"{exception.GetType().FullName}\r\n{exception.Message}\r\n{exception.StackTrace}"); } } // Send a trace activity, which will be displayed in the Bot Framework Emulator await turnContext.TraceActivityAsync("OnTurnError Trace", exception.Message, "https://www.botframework.com/schemas/error", "TurnError"); }; }
private async Task ProcessTurnError(ITurnContext turnContext, Exception ex) { if (logger != null) { logger.LogError(ex, $"[OnTurnError] Error : {ex.Message}"); } await turnContext.SendActivityAsync("The bot encountered an error"); await turnContext.TraceActivityAsync("OnTurnError Trace", ex.Message, "https://www.botframework.com/schemas/error", "TurnError"); if (conversationState != null) { await conversationState.DeleteAsync(turnContext); } }
public SkillAdapterWithErrorHandler(IConfiguration configuration, ILogger<SkillAdapterWithErrorHandler> logger, IStorage storage, UserState userState, ConversationState conversationState) : base(configuration, logger) { this.UseStorage(storage); this.UseState(userState, conversationState, false); OnTurnError = async (turnContext, exception) => { // Log any leaked exception from the application. logger.LogError(exception, $"[OnTurnError] unhandled error : {exception.Message}"); // Send a message to the user var errorMessageText = "The skill encountered an error or bug."; var errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.IgnoringInput); await turnContext.SendActivityAsync(errorMessage); errorMessageText = "To continue to run this bot, please fix the bot source code."; errorMessage = MessageFactory.Text(errorMessageText, errorMessageText, InputHints.ExpectingInput); await turnContext.SendActivityAsync(errorMessage); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception ex) { logger.LogError(ex, $"Exception caught on attempting to Delete ConversationState : {ex}"); } } // Send and EndOfConversation activity to the skill caller with the error to end the conversation // and let the caller decide what to do. var endOfConversation = Activity.CreateEndOfConversationActivity(); endOfConversation.Code = "SkillError"; endOfConversation.Text = exception.Message; await turnContext.SendActivityAsync(endOfConversation); // Send a trace activity, which will be displayed in the Bot Framework Emulator // Note: we return the entire exception in the value property to help the developer, this should not be done in prod. await turnContext.TraceActivityAsync("OnTurnError Trace", exception.ToString(), "https://www.botframework.com/schemas/error", "TurnError"); }; }
/// <summary> /// Initializes a new instance of the IntentBotAdapter class /// </summary> /// <param name="credentialProvider"></param> /// <param name="conversationState"></param> /// <param name="userState"></param> /// <param name="logger"></param> public IntentBotAdapter(ICredentialProvider credentialProvider, ConversationState conversationState, UserState userState, ILogger <BotFrameworkHttpAdapter> logger) : base(credentialProvider) { if (conversationState == null) { throw new ArgumentNullException(nameof(credentialProvider)); } if (conversationState == null) { throw new ArgumentNullException(nameof(conversationState)); } if (userState == null) { throw new ArgumentNullException(nameof(userState)); } // Enalbe state auto save this.Use(new AutoSaveStateMiddleware(conversationState, userState)); // Teams middleware this.Use(new TeamsMiddleware(credentialProvider)); // Configure typing middleware here: https://github.com/microsoft/botbuilder-dotnet/issues/2407 this.Use(new ShowTypingMiddleware(200)); // Add global error handling this.OnTurnError = async(turnContext, exception) => { // Log any uncaught exception, and send a generic error back to the user. logger.LogError(exception, $"Uncaught exception: {exception.Message}"); await turnContext.SendActivityAsync($"Uh oh, something is wrong: {exception.Message}"); try { // Try to delete clean up the conversation state for the current conversation // to prevent the bot from getting stuck in a error-loop caused by the bad state. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError(e, $"Exception attempting to Delete ConversationState: {e.Message}"); } }; }
public AdapterWithErrorHandler(IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, ConversationState conversationState = null) : base(configuration, logger) { this.MiddlewareSet.Use(new RegExpRecognizerMiddleware() .AddIntent("search", new Regex("search picture(?:s)*(.*)|search pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("share", new Regex("share picture(?:s)*(.*)|share pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("order", new Regex("order picture(?:s)*(.*)|order print(?:s)*(.*)|order pic(?:s)*(.*)", RegexOptions.IgnoreCase)) .AddIntent("help", new Regex("help(.*)", RegexOptions.IgnoreCase)) ); //read Cosmos DB settings from appsettings.json CosmosDbStorageOptions dbConfig = new CosmosDbStorageOptions() { AuthKey = configuration.GetSection("CosmosDB").GetValue <string>("Key"), CollectionId = "Transcript", CosmosDBEndpoint = new Uri(configuration.GetSection("CosmosDB").GetValue <string>("EndpointURI")), DatabaseId = configuration.GetSection("CosmosDB").GetValue <string>("DatabaseName"), }; this.MiddlewareSet.Use(new TranscriptLoggerMiddleware(new CosmosTranscriptStore(dbConfig))); OnTurnError = async(turnContext, exception) => { // Log any leaked exception from the application. logger.LogError($"Exception caught : {exception.Message}"); // Send a catch-all apology to the user. await turnContext.SendActivityAsync("Sorry, it looks like something went wrong."); if (conversationState != null) { try { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } catch (Exception e) { logger.LogError($"Exception caught on attempting to Delete ConversationState : {e.Message}"); } } }; }
public AdaptiveBotAdapter(ICredentialProvider credentialProvider, IConfiguration configuration, ILogger <BotFrameworkHttpAdapter> logger, IStorage storage, UserState userState, ConversationState conversationState, ResourceExplorer resourceExplorer) { this.Use(new RegisterClassMiddleware <IConfiguration>(configuration)); this.UseStorage(storage); this.UseState(userState, conversationState); this.UseResourceExplorer(resourceExplorer); this.UseLanguageGeneration(resourceExplorer); this.UseAdaptiveDialogs(); this.OnTurnError = async(turnContext, exception) => { if (conversationState != null) { // clear the conversationState to ensure that the next request for user will be routed to a new conversation await conversationState.DeleteAsync(turnContext); } }; }
public AdapterWithErrorHandler( ICredentialProvider credentialProvider, ConversationState conversationState = null) : base(credentialProvider) { OnTurnError = async(turnContext, exception) => { // Send a catch-all apology to the user. await turnContext.SendActivityAsync("Sorry, it looks like something went wrong."); if (conversationState != null) { // Delete the conversationState for the current conversation to prevent the // bot from getting stuck in a error-loop caused by being in a bad state. // ConversationState should be thought of as similar to "cookie-state" in a Web pages. await conversationState.DeleteAsync(turnContext); } }; }