How to separate errors from a query in an expressjs api

Asked

Viewed 38 times

1

What is the correct method to separate errors from a query?

The current code compares the error manually with the message generated by mysql, in case the query may go wrong for several reasons, instead of returning a log and error 500 like this :

{
   err: 'ER_DUP_ENTRY',
   code: 500
}

return an error like this :

{
   msg: 'Username already in use',
   code: 500,
};

Detail :

mysql driver: mysql2

sample code :

const register = async (username, password) => {
    try {
        const hashedPassword = await bcrypt.hash(password,12);
        const user = {
            username,
            password: hashedPassword
        };
        await db.query(queryRegister, user);
        return {
            msg: 'User registered with success',
            code: 200,
        };
    } catch(err) {
        if(err.code === 'ER_DUP_ENTRY') {
            return {
                msg: 'Username already in use',
                code: 500,
            };   
        }
    }
}

1 answer

2


There’s no way to change the output error generated by driver Mysql. You need to create some way to turn error codes into friendlier messages.

An example to do this:

function beautifyError(code) {
  const dict = {
    'ER_NOT_FOUND': 'Registro não encontrado.',
    'ER_DUP_ENTRY': 'Duplicada.',
    'ER_DEFAULT': 'Houve um erro desconhecido.'
  };

  if (!dict.hasOwnProperty(code)) {
    return dict['ER_DEFAULT'];
  }

  return dict[code];
}

console.log(beautifyError('ER_NOT_FOUND'));
console.log(beautifyError('ER_UNKNOWN'));

In your example, it would look something like this:

function beautifyError(code) {
  const dict = {
    'ER_NOT_FOUND': 'Registro não encontrado.',
    'ER_DUP_ENTRY': 'Duplicada.',
    'ER_DEFAULT': 'Houve um erro desconhecido.'
  };

  if (!dict.hasOwnProperty(code)) {
    return dict['ER_DEFAULT'];
  }

  return dict[code];
}

const register = async (username, password) => {
  try {
    const hashedPassword = await bcrypt.hash(password, 12);
    const user = {
      username,
      password: hashedPassword
    };

    await db.query(queryRegister, user);

    return {
      msg: 'User registered with success',
      code: 200
    };
  } catch ({ code, status = 500 }) {
    const msg = beautifyError(code);
    return { msg, code: status };
  }
};

I imagine it’s valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.