jazzedge
7/28/2017 - 10:17 AM

Bot - Error Handling & Global Error Handling

Bot - Error Handling & Global Error Handling

// See:https://github.com/Microsoft/BotBuilder-Samples/blob/master/Node/core-MultiDialogs/README.md
// also: https://github.com/Microsoft/BotBuilder/issues/1710

Handling dialog errors

Errors can be signaled from child dialogs using session.error. This will signal the error via an on('error', err) event, for both the bot object and the session object. In flights.js we are signalling an error which the parent dialog handles using session.on('error'), as shown in app.js:

session.on('error', function (err) {
    session.send('Failed with message: %s', err.message);
    session.endDialog();
});
You can also listen for errors triggered on any level by subscribing to the error event exposed by the UniversalBot. Check out how to log bot errors globally:

// Globally log any bot errors into the console
bot.on('error', function (e) {
    console.log('And error ocurred', e);
});

// The message "Oops. Something went wrong and we need to start over." is only shown when Session.error() is called and the message
// itself can be customized by you. Typically this is only called in two situations: 1) we called some external service like LUIS and
// encountered a problem. 2) your bots code threw an exception that you didn't catch.

// You can avoid the second case by simply adding try{}catch{} statements to you code. You can also add bot.on('error', function (err)
// {}); to your code and you'll be told anytime an error is detected although you can't prevent the default logic from executing.

// The other thing you should know about session.error() is that it ends the current conversation to prevent the user from getting 
// stuck. That's why it sends a message to them to tell them that something went wrong. If you truly want to alter this behavior you can 
// use a piece of middleware to provide your own implementation:

bot.use({
     botbuilder: function (session, next) {
          session.error = function (err) {
              // Do something custom
          };
          next(); 
     }
});