Javascript 无法读取对象的值

Javascript 无法读取对象的值,javascript,exception,Javascript,Exception,我正在编写一个函数,其中我想做一些事情,如果它出错,捕获它的状态代码。下面是我的职责 client.leads.listBy({ email: lead.email }).then((res) => { //do somthing }).catch((err) => { if (typeof err.statusCode != 'undefined') { console.log("the"); } else {

我正在编写一个函数,其中我想做一些事情,如果它出错,捕获它的状态代码。下面是我的职责

 client.leads.listBy({
     email: lead.email
 }).then((res) => {

    //do somthing
 }).catch((err) => {

     if (typeof err.statusCode != 'undefined') {
         console.log("the");
     } else {
         console.log(err);
     }


 });
这是我得到的例外

Error: {"statusCode":404,"body":{"type":"error.list","request_id":"b1fgpg7ovmtufdj5trn0","errors":[{"code":"not_found","message":"User Not Found"}]},"headers":{"cache-control":"no-cache","content-type":"application/json; charset=utf-8","date":"Fri, 09 Feb 2018 20:12:53 GMT","server":"nginx","set-cookie":["_mkra_ctxt=2c440af4e2742721616aff3205dba2a6--404; path=/; max-age=5; HttpOnly; secure"],"status":"404 Not Found","strict-transport-security":"max-age=31557600; includeSubDomains; preload","vary":"Accept-Encoding","x-content-type-options":"nosniff","x-frame-options":"SAMEORIGIN","x-intercom-version":"e371d2ed50f488065fd36fb728b849d66e3846c2","x-ratelimit-limit":"83","x-ratelimit-remaining":"36","x-ratelimit-reset":"1518207180","x-request-id":"b1fgpg7ovmtufdj5trn0","x-runtime":"0.049997","x-xss-protection":"1; mode=block","transfer-encoding":"chunked","connection":"Close"},"request":{"uri":{"protocol":"https:","slashes":true,"auth":null,"host":"api.intercom.io","port":null,"hostname":"api.intercom.io","hash":null,"search":"?email=nicole.goncalves%40mvfglobal.com","query":"email=nicole.goncalves%40mvfglobal.com","pathname":"/users","path":"/users?email=nicole.goncalves%40mvfglobal.com","href":"https://api.intercom.io/users?email=nicole.goncalves%40mvfglobal.com"},"method":"get","headers":{"Accept":"application/json","User-Agent":"intercom-node-client/2.0.0","authorization":"Basic ZEc5ck9tSTVOakUzTW1JNFgyWmlNRGhmTkdZeVlWODVZVEF6WDJOa01qazROakl3T0RRME16b3hPakE9Og==","content-length":0}}}

我试图通过
err.statusCode
访问此文件,但它不起作用。如何获取状态代码。它总是转到else条件并打印错误,因为您试图访问字符串的
statusCode
,所以出现此错误。我猜
client.leads.listBy
确实将错误字符串化,并调用
抛出新错误(stringifiedObj)
,因此最终无法在
catch
块访问其属性。否则您将得到[Object]作为输出

好的,我给你准备好了。您在控制台输出中看到的是一条错误消息,它是一个字符串。下面是要在
catch
块中执行的操作,以检查实际属性:

const errObj = JSON.parse(err.message)
if (errObj.statusCode !== undefined) {
     console.log("the");
} else {
     console.log(err);
}

您确定这就是代码记录err对象的确切位置吗?因为这对我来说很好:@ChrisG我100%确定。这是唯一获得404状态代码的函数。我在下面添加了另一个日志。也是。否类型为object
Worker.Node.2b0c2c75-a484-4497-acdb-d1310408c93e[0]对象
异常本身确实是一个对象。您在控制台中得到的是它的消息,它是一个字符串。我将编辑我的答案,使其更清楚如何去除错误:part cant replace收到一个错误,说
err.replace不是一个函数
我所做的
var ret=err.replace('Error:','');var arr=JSON.parse(ret);控制台日志(arr.statusCode)刚刚想出你应该做什么(见我的答案)。对不起,这有误导性。由于某种原因,我把一切都搞错了。它给了我这个错误
位置0处JSON中意外的标记E
无法以这种方式解析它