没有显示返回拒绝响应 - nodejs

时间:2018-02-28 02:38:13

标签: javascript node.js

我对节点js和承诺都是全新的。我从客户端和主体调用API如下

    return dbNameses.checkNamesAvailable(request.body.data.attributes.Names)
.then((results) => {
  if(results <= 0) {
    return dbNames.saveNewNames(request.body.data.attributes.Names).then((saveresults) =>{
      return response.setStatusCode(200).setPayload({
        message:"Name is saved"
    })
    }).catch()
  }else {
    return response.setStatusCode(500).setPayload({
      message:"Name is already exist"
   })
  }
}).catch(err => {
  return response.setStatusCode(400).setPayload({
     message : err,
     data : err.message
})

和saveNewNames函数如下

    function saveNewNames(
  Names /* :?string | void */ 
)/* :Promise<string> */ {
  const connection = createConnection()
  return new Promise((resolve, reject) => {

    var newNames = [];

    var seperatedNames = Names.split(',')
    if(seperatedNames.length>2){

      var firstNameLine = capitalFirstLetter(seperatedNames[0])
      var secondNameLine = seperatedNames[1].toUpperCase()
      var thirdNameLine = seperatedNames[2].toUpperCase()

      var displayNames = firstNameLine + ',' + secondNameLine + ',' + thirdNameLine

        newNames.push({
        "Names": Names,
        "display": displayNames
      })

       var NamesToDb = JSON.stringify(newNames).replace(/]|[[]/g, ''
     )

     const sql = `
     INSERT INTO Names
     (
       names
     )
     VALUES
     (
       ?
     )`
      const values = NamesToDb
      const query = connection.query(sql, values, (error, results, fields) => {
      connection.end()
      if (error) {
        return reject(error)
      }
        resolve(results)
      })
    }else{
      return reject(new Error('Please add a valid names'))

    }})
    .catch((err) => {
      reject("There was an error adding Names to database", err.message)
      throw err
    })
}

当用户添加非格式的无效名称时,会返回拒绝(新错误(&#39;请添加有效名称&#39;))部分。并返回400错误。但是我没有在消息中收到错误消息:错误或数据:错误消息,而不是我收到的数据:错误消息&#34;拒绝未定义&#34;

有人可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

请检查捕获区块:

 return dbNameses.checkNamesAvailable(request.body.data.attributes.Names)
.then((results) => {
  if(results <= 0) {
    return dbNames.saveNewNames(request.body.data.attributes.Names).then((saveresults) =>{
      return response.setStatusCode(200).setPayload({
        message:"Name is saved"
    })
    }).catch(err => {
      return response.setStatusCode(400).setPayload({
        message : err,
        data : err.message
      })
  } else {
    return response.setStatusCode(500).setPayload({
      message:"Name is already exist"
   })
  }
}).catch(err => {
  return response.setStatusCode(400).setPayload({
     message : err,
     data : err.message
})