Search code examples
twiliotwilio-functions

getting callback function error in twilio functions


My debugger keeps on sending me a callback error (see img link below) for this function. I also would like to continue from my function back to studio, the studio docs say I need "A successful return (HTTP 20X)" what am I missing

    exports.handler = function(context, event, callback) {

const client = require('twilio')();
const msg = event.Msg;
client.messages
  .create({
     body: msg,
     from: '+17322222222',
     to: '+13477777777'
   })
  .then(message => console.log(message.sid));
};

Error msg from Debugger

if I insert callback() at end of code, I get a successful return but the message doesn't get sent then.

exports.handler = function(context, event, callback) {

const client = require('twilio')();
const msg = event.Msg;

client.messages
  .create({
     body: msg,
     from: '+17322222222',
     to: '+13477777777'
   });

  callback();
};

Solution

  • You need to have the callback execute after the message is successfully sent.

    This can be done using promises or async/await syntax as shown below:

    exports.handler = function(context, event, callback) {
    
       let twilioClient = context.getTwilioClient();
    
       twilioClient.messages
         .create({
           body: 'Hello World',
           to: '+13477777777',
           from: '+17322222222',
         }).then(message =>  {
           console.log(message.sid);
           callback(null, {result: "success"});
         })
        .catch(error => {
           console.log(error);
           callback({result: "error"});
        });
    };
    

    or

    exports.handler = async function(context, event, callback) {
    
        let twilioClient = context.getTwilioClient();
    
        let sendSMS = () => { 
            try {   
            let result = twilioClient.messages
            .create({
               body: 'Hello World',
               to: '+13477777777',
               from: '+17322222222',
             });
             return result;
            } catch(e) {
              console.log(e);
              callback(e);
            }
        };
    
        let result = await sendSMS();
        callback(null, result);
    };