【问题标题】:can someone get the status of an error during try and catch? Node.js有人可以在 try and catch 期间获得错误状态吗?节点.js
【发布时间】:2019-10-30 10:38:40
【问题描述】:

我正在尝试获取任何错误的状态 在 try-catch 方法中可能吗?

例子

try{
//something to do
}
catch(e){
console.log(e.status)
}

我正在尝试在下面的代码中实现它

try {
      entryModel.entries.push(newEntry);
      return res.status(201).json({
        status: 201,
        message: 'entry successfully created',
        data: {
          newEntry,
        },
      });
    } catch (e) {
      return res.status(e.status).json({
        status: e.status,
        error: e.message,
        data: {
          newEntry,
        },
      });
    }

【问题讨论】:

    标签: node.js api try-catch nodes


    【解决方案1】:

    一般来说,这个catch错误是关于数据库的,在universal中,status_code是422,消息是422 unprocessable entity。但更具体地说,您可以传递错误对象消息:

    catch (e) {
      return res.status(422).json({
        status: 422,
        error: e.message,
        data: {
          newEntry,
        },
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多