Ryan Bester
Ryan Bester

Reputation: 51

Cannot read property 'catch' of undefined

I am trying to use Argon2 encryption in Node, but when I try to encrypt a string, I get this error:

Cannot read property 'catch' of undefined

I have tried handling the errors from the promise returned by the argon2.hash function, but it still does not work.

This is my code so far:

argon2.hash('password', {type: argon2.argon2id})
    .then(hash => {
        // do something with the hash
    }).catch(err => {
        // Handle the error
    });

Could anyone please help me with fixing this error?

Upvotes: 5

Views: 13376

Answers (3)

Stefan
Stefan

Reputation: 12270

In my case I got that error message because I

a) spied on some async method

spyOn(sut,'myAsyncMethod')

b) later appended .catch() to the original method call and forgot to extend the spy to return a value/promise.

Returning a promise from the spy solved my issue:

spyOn(sut,'myAsyncMethod').and.returnValue(new Promise(resolve=>resolve()));

Upvotes: 3

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

Try the following instead:

argon2.hash('password', {type: argon2.argon2id})
  .then(hash => {
    // do something with the hash
}, err => {
    // Handle the error
});

The second parameter to a then clause is the onError handler.

Upvotes: 0

Gal Naor
Gal Naor

Reputation: 2397

It throws an exception, it does not return a promise. As such, there is no promise object on which the then(…).catch(…) methods could be invoked.

To catch it, you would need an actual try/catch block

from argon2 github page, you should do this:

const argon2 = require('argon2');

try {
  const hash = await argon2.hash("password");
} catch (err) {
  //...
}

Upvotes: 1

Related Questions