简体   繁体   中英

error handle in promise nodejs + postgresql

I just start learning nodejs below is my code ...
Q1. Do I handle the error message correct way with insertUserPendingBase() ??
I check the return message if equal success or not. And if so what is the then can do in this example?

Q2. I use pg when I do execute the query do I need to do anything for prevent SQL injection? I saw in document there's no need, but I'm not sure..

any suggestions can improve my code will be welcome

routes

var express = require('express');
var router = express.Router();
var co = require('co');

// .. post
var insertUserPendingBase = function(token) {
  return new Promise(function (fulfill, reject){
    var query = "INSERT INTO user_pending_base (user_pending_email,user_pending_password,token_timestamp,token) VALUES ('" + user_email + "','" + user_password + "', CURRENT_TIMESTAMP,'" + token + "')";
    dbClient.query(query, function(err, result) {
      if (err) {
        reject(err);
      } else {
        fulfill('success');
      }
    });
  });

  // .then(function(value) {
  //   console.log(value);
  //   throw "error message";
  // }).catch(function(e) {
  //   console.log(e);
  // });
}

co(function *() {
  // ...
  var insertUserPendingBaseResult = yield insertUserPendingBase(generateTokenResult);

  console.log('insertUserPendingBaseResult:'+insertUserPendingBaseResult);
  if (insertUserPendingBaseResult == 'success') { // handle error like this ??

  }

  res.render('Account/Register/Index', {
    partials: {
      Content: 'Account/Register/Content',
    }
  });
}).catch(onerror);

function onerror(err) {
  console.error(err.stack);
}

Update

If I change fulfill(result) instead of fulfill('success') I will get below object but there's no message about fail or success

{ command: 'INSERT',
  rowCount: 1,
  oid: 0,
  rows: [],
  fields: [],
  _parsers: [],
  RowCtor: null,
  rowAsArray: false,
  _getTypeParser: [Function] }

Update 2

I find a way use try and catch inside co(function *() like below, but I'm not sure is this the best way make a clean code ?

co(function *() {
... 
try {
  var insertUserPendingBaseResult = yield insertUserPendingBase(generateTokenResult);
  // if success ...

} catch (err) {
  // if fail
  console.log(err);
}

Cannot comment on SQL injection, but fulfill('success') must be fulfill(result) .

To handle success and failure of the promise you should use then and catch , no need for generators:

insertUserPendingBase.then(function(result) { /* handle result here */ })
                     .catch(function(ex) { /* handle exception here */ })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM