I'm Joe Too
I'm Joe Too

Reputation: 5840

Creating error/result function in node

I'm having trouble understanding how to create functions that would return in the format of (err, result) for an Express app.

My current db query function is:

pool.query(
  'SELECT id FROM users WHERE email = ? LIMIT 1',
  [email],
  (results) => { // I'd like this to be (err, results)
    if(results instanceof Error){...}
  }
})

In my db.js file, pool looks like this:

module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        new Error('No database connections available in pool')
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release()
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            new Error('Bad query')
          } else {
            cb(results)
          }
        })
      }
    })
  }
}

For this and other functions, I'd like to return a proper Error if there is one, and have my callback listen for err, result as parameters.

I tried using new Error('Bad query') but that came back as the first variable in my callback no matter what (which is how I ended up with instanceof Error.

How do you structure a callback and response so that your callback can be in the err, result format and check for/handle errors properly on functions you're creating? (I understand how to use it for modules already in this format - I'm talking about writing/formatting your own code.)

Thanks!

Upvotes: 0

Views: 88

Answers (1)

jfriend00
jfriend00

Reputation: 707318

You can do it like this:

module.exports = {
  query: (query, args, cb) => {
    pool.getConnection( (err, connection) => {
      if(err){
        cb(new Error('No database connections available in pool'));
      } else {
        connection.query(query, args, (error, results, fields) => {
          connection.release();
          // I got a MySQL error here and I'd like to handle it in my callback function
          if(error){
            cb(new Error('Bad query'));
          } else {
            cb(null, results);
          }
        });
      }
    });
  }
}

You always pass the error value as the first argument to the callback and, if there is a result, you pass it as the second. Then, within the callback, you check to see if err is non-null and, if so, there is an error. If it's null, then the second argument contains the result.

Note that by not returning or including the actual err value that the database gave you, you may be hiding useful information (like why the query failed).


Then, where you use this, you do something like this:

let query = 'SELECT id FROM users WHERE email = ? LIMIT 1'; 
pool.query(query, [email], (err, result) => {
    if (err) {
        // handle error here
    } else {
        // process result here
    }
});

Upvotes: 1

Related Questions