How to separate the errors of a query into an api expressjs

1

What is the correct method of separating errors from a query?

The current code compares the error manually with the message generated by mysql, in case the query can 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:

Driver mysql: 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,
            };   
        }
    }
}
    
asked by anonymous 11.10.2018 / 21:12

1 answer

2

There is no way to change the output error generated by the driver of 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 looks more or less 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 to be valid.

    
12.10.2018 / 22:49