James111 James111 - 5 months ago 22
Node.js Question

Where to handle promise errors in a REST api?

For instance lets take a

login
flow, where a user can login with
facebook
or
email+password
, if the user logs in with
facebook
first, a
user credential + user entity
is created under that
facebook [email + id]
.

The same user may forget they used
facebook
intially and try to create an
email
login. Now what happens is that user will have to
sign in
with the
facebook
account to be able to create the new
email credential
for the
user entity
.

Todo this I've got two classes, 1 (login_handler.js), 2 (user.js, which handles all the queries).

Inside my
user.js
class I've got:

Basically what this does is, checks if the user exists, if it exists and the userType (the type of account they're logging in with) is different to the accountType (email, facebook) in the database. I'm wondering if I should be handling this type of logic inside my promise chain (login_handler.js) or directly in the class?

checkUserExists () {
console.log ("BEFORE ERROR")
const {externalId, email, password, userType} = this;
var query;
if (this.userType == 'email')
query = `select * from content_usercredential where email = '${email}' AND secret = '${password}'`;
else if (this.userType == 'facebook'){
query = `select * from content_usercredential where email = '${email} AND externalId = '${externalId}'`;
}

return new Promise ( (fulfill, reject) => {
conn.query(query, (err, user) => {
if (user.accountType == 'facebook' && this.userType == 'email') {
// Should I handle this here, or in my login_handler promise chain?
this.res.json("you must login with facbeook", session data here...so when they sign in we can pick up where we left off);
throw new Error ("Return confirmation object to client");
});
});


login_handler.js

Should I be handling and throwing an error here so the rest of my promise chain doesn't execute, or should I be throwing an error directly where it happens (in the user.js class).

User.checkUserExists()
.then ( () => {
// Should I handle here OR in my user.js class file?
if (User.needsToConfirm) {
this.res.json("you must login with facbeook", session data here...so when they sign in we can pick up where we left off);
throw new Error("OR should I return the confirmation object here?"});
}
}).then( () => return createNewUserEntity())
.then( () => return createUserCredential())

Answer

Your two classes have a clear responsibility. User.js accessing the data layer and login_handler.js handling login requests and responses.

Think some time in the future you have to replace your data access layer (User.js) or your login service layer (login_handler.js). Changing the data layer would cause reimplementing the response and changing the service layer would cause to change the data layer because you will have to re-implement the response.

Therefore make sure your classes have always a clear responsibility and a minimal set of common interaction.

Comments