JillAndMe
JillAndMe

Reputation: 4561

I wrapped with try-catch block but app crashed

I am trying to throw an error in the following syntex:

  if(err) throw err

What I expect is to print the log by the line of "console.log(err)" instead of app crashed.

However, this occurs an error with app crashed and says

throw err; // Rethrow non-MySQL errors
        ^

Error: Error: ER_DUP_ENTRY: Duplicate entry 'test4' for key 'nickname_UNIQUE'

I cannot figure out why this happens and need helps from the experties.

code :

 api.post('/', (req, res) => {
    const email = req.body.email
    const nickname = req.body.nickname
    const password = req.body.password
    const thumbnail = req.file
    const type = req.body.type

    const hasherCallback = (err, pass, salt, hash) => {
      if (err) throw err

      const sql = `INSERT INTO users set ?`
      const fields = { nickname, email, 'password': hash, salt, thumbnail, type }
      const queryCallback = (err) => {
        if (err) throw err

        return res.json(messages.SUCCESS_MSG)
      }

      conn.query(sql, fields, queryCallback)
    }
    try {
        return hasher({ password }, hasherCallback)
    } catch (err) {
      //handle errors here
      console.log(err)
    }
  })

  return api
}

//Error : Error: Error: ER_DUP_ENTRY: Duplicate entry 'test4' for key 'nickname_UNIQUE'

Upvotes: 0

Views: 384

Answers (2)

JillAndMe
JillAndMe

Reputation: 4561

I found that I cannot throw errors in async function so I tried using callback.

api.post('/', (req, res) => {
    const email = req.body.email
    const nickname = req.body.nickname
    const password = req.body.password
    const thumbnail = req.file
    const type = req.body.type

    const errorHandle = (callback) => {
      const hasherCallback = (err, pass, salt, hash) => {
        if (err) return callback(err)

        const sql = `INSERT INTO users SET ?`
        const fields = { nickname, email, 'password': hash, salt, thumbnail, type }
        const queryCallback = (err) => {
          if (err) return callback(err)

          return res.json(messages.SUCCESS_MSG)
        }
        conn.query(sql, fields, queryCallback)
      }

      return hasher({ password }, hasherCallback)
    }

    return errorHandle((err) => {
      //This one equals console.log({ status: 'error' message: err })
      return res.status(500).json(messages.ERROR(err))
    })
  })

This prints log what I want instead of app crashed.

 {
    "status": "error",
    "message": {
        "code": "ER_DUP_ENTRY",
        "errno": 1062,
        "sqlMessage": "Duplicate entry 'test4' for key 'nickname_UNIQUE'",
        "sqlState": "23000",
        "index": 0,
        "sql": "INSERT INTO users SET `nickname` = 'test4', `email` = '[email protected]', `password` = 'FXxSpPBNFfL1KGS0sWn19N191Hj0FXtnCWwMspneVIvwB5UgPBI0MjBskEnHby357j/3VKWM7ffi/5yD5CiIRyAGMWnTaStzbVX/hhD1/y91UW9b8etWpV5koKcn9QsmD9BozX1+wkve66lTNoFUHDWA0BDj4j8O7ltsD4698LQ=', `salt` = 'cu7GlOjK4drxV/SD4CBJtiW5yirc5/TpaAroCBbCQtOy4Asr8rGvTrxArXHmPH6ADTtHlXvUEEoeUD73LS654Q==', `thumbnail` = NULL, `type` = 'local'"
    }
}

Upvotes: 0

Peter H
Peter H

Reputation: 901

The throw statement throws a user-defined exception. Execution of your function will stop and nothing will be executed from this point onwards.

See this website for help on the throw keyword. Also take the time to read about the throw new Error as this might be what you need instead of throw. This link may also be of help

In terms of why the error is occurring, the MySQL error is telling you you are inserting duplicate data into your users table. The database is rejecting it because a record already exists with the nickname value of 'test4' in the table.... So you are not allowed to insert another user with the same nickname of 'test4' into the table.

Why you may ask? This is because You have an index on the table which requires the nickname to be unique.

Two options you could use are as follows:

  1. Add more code to you javascript telling your user that if the nickname is already taken by another user, request that they choose another nickname and retry.
  2. Allow duplicate nicknames by removing the unique nickname requirement on the table if you want to allow the same nickname to be inserted more than once. To do this you'll need to modify the index on the table. This may be dangerous and not suitable if your other table fields don't have a value that is unique.

Good luck and happy coding.

Upvotes: 1

Related Questions