Custom Error Messages and Exception Handling in Bot Framework Composer

538 Views Asked by At

I am trying to have Custom Error messages for any any Exceptions thrown by Bot Framework Composer Bot. As the custom runtime of Composer project does not have bot.cs file, it is not possible to implement OnturnError. I have tried to add it in Startup.cs but it is not working. Is there a way I can implement this ?

I have also tried adding a Error handling class inheriting from cloudAdapter and adding it as a service in Startup.cs.

 public class AdapterWithErrorHandler : CloudAdapter
    {
        public AdapterWithErrorHandler(BotFrameworkAuthentication auth, ILogger<IBotFrameworkHttpAdapter> logger, ConversationState conversationState = default)
            : base(auth, 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 = "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");
            };
        }
    }

Startup .cs

   services.AddSingleton<IBotFrameworkHttpAdapter, AdapterWithErrorHandler>();

1

There are 1 best solutions below

0
Vinoth Rajendran On

You can use "Error occurred event" to handle errors and custom error messages, steps on how to handle exceptions in BotComposer