title: Unhandled rejection TypeError: Cannot read property 'toString' of undefined
body: <p>I'm sending a base64 encoded token to my API. It's an id token from google. When the string is valid it all works fine but i'm actually trying to setup proper error handling. Adding some extra characters to the string throws the TypeError.</p>
  
  <p>I've logged the result from the encoding and the buffer and it's all defined. Anyone able to tell what i'm doing wrong?</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function(payload) {
    var config = request.getAsync('https://accounts.google.com/.well-known/openid-configuration')
      .then(function(result) {
        var response = JSON.parse(result.body);
        return request.getAsync(response.jwks_uri);
      })
      .then(function(result) {
        return JSON.parse(result.body);
      })
      .caught(SyntaxError, function(e) {
        throw e;
      })
  
    var header = new Promise(function(resolve, reject) {
        var segments = payload.id_token.split('.');
        try {
          resolve(JSON.parse(base64urlDecode(segments[0])));
        } catch (e) {
          reject(e);
        }
  
      })
      .caught(SyntaxError, function(e) {
        throw e;
      })
  
    return Promise.join(config, header, function(response, header) {
      return new Promise(function(resolve, reject) {
        var key = '';
        for (var i = 0; i &lt; response.keys.length; i++) {
          if (response.keys[i].kid === header.kid) {
            key = response.keys[i];
            break;
          }
        }
  
        if (jws.verify(payload.id_token, key)) {
          resolve();
        } else {
          reject();
        }
      });
    });
  }
  
  function base64urlDecode(str) {
    return new Buffer(base64urlUnescape(str), 'base64').toString();
  };
  
  function base64urlUnescape(str) {
    str += Array(5 - str.length % 4).join('=');
    return str.replace(/\-/g, '+').replace(/_/g, '/');
  }</code></pre>
  </div>
  </div>
  </p>