ory / hydra-js

DOES NOT WORK WITH VERSIONS > 0.10.0 - A simple library to help you build node-based identity providers that work with Hydra.
19 stars 8 forks source link

Unhandled promise rejections & friends :) #5

Closed DanielSmedegaardBuus closed 7 years ago

DanielSmedegaardBuus commented 7 years ago

Just a couple of minor edits.

Cheers! :)

DanielSmedegaardBuus commented 7 years ago

I'll fix the undefined error, and create a failing test. The test won't be this week, though, I have to finish a project today and am leaving for Luxembourg tomorrow, so it'll be next week :)

About the Promise thing. Yes, when an error is thrown inside a Promise, it's automagically converted to a rejection. But:

  getKey(set, kid) {
    return new Promise((resolve, reject) => {
      return this.authenticate().then(() => {
        request.get(`${this.endpoint}/keys/${set}/${kid}`).authBearer(this.token.token.access_token).end((err, res) => {
          if (err || !res.ok) {
            reject({ error: 'Could not retrieve validation key: ' + error })
            return
          }
          resolve(res.body.keys[0])
        })
      }, reject)
    })
  }

You're first returning a new Promise, on which you're passed in the resolve and reject functions. The inner Promise is returned by this function, but that doesn't chain it to the outer Promise, its return value does not apply to it, it'll just wait for resolve() or reject() to be called.

Then, if OAuth2.create() throws inside the authenticate() method, the Promise will catch it and call its own reject(err). However, since return this.authenticate(...) is only providing a callback to resolve, and there's no .catch() clause either, the reject(err) call from authenticate() ends up in the void.

You could also do return this.authenticate().then(...).catch(reject), and AFAICT just return that directly rather than wrapping it in the outer Promise, but I may be missing something...

aeneasr commented 7 years ago

Awesome, thanks for explaining that!

DanielSmedegaardBuus commented 7 years ago

Today was cake day, so I had a little while while eating my brownie, so the tests are up. I had to update jest to v20, since that's when expect.reject was introduced :)

aeneasr commented 7 years ago

Awesome, thank you for your contribution!

DanielSmedegaardBuus commented 7 years ago

Oh no, thank you for making this module :)