Monday, 8 May 2017

How to use Insert error callback for pg in node.js(npm)

I'm a korean. Thanks.

I am using postgresql in node.js. ( npm install pg in koa@2 ) I want to get a 'primary key' duplicate error as a callback when I insert it. So I want to handle id duplicate error on the server.

Is there a way?

Ps.

current code is

pool.connect().then(client => {
      const query1 = 'INSERT INTO users_tb (id, email, username, password, created_at) VALUES ( $1, $2, $3, $4, CURRENT_TIMESTAMP)'
      client.query(query1, ['6', 'test@naver.com', 'isman', 'password9999'])
      .then(response => {
        client.release()
        console.log('hello from', response.rows[0])
      })
      .catch(error => {
        client.release()
        console.error('1. message >> ', error.message)
        console.error('2. stack >> ', error.stack)
      })
    })
  }

Currently, an error message such as

duplicate key value violates unique constraint 'users_pkey'

is generated. I want to handle this and have the user enter a different id.



via J. thomas

No comments:

Post a Comment