You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法读取对象值及函数异常状态码捕获失败问题咨询

Troubleshooting Your Two Technical Issues

I’ve run into both of these issues myself, so let’s walk through fixes step by step!


1. Fixing the "Can't read the value of an object" Error

This error almost always pops up for one of two reasons:

  • The object you’re trying to access is null or undefined
  • You’re trying to access a nested property (like obj.user.email) where an upper-level property (e.g., obj.user) doesn’t exist

Example of the Problem

const user = getSomeUser(); // Imagine this returns null
console.log(user.email); // Boom! "Can't read property 'email' of null"

Quick Fixes

  • Use the optional chain operator (?.) (ES2020+) – this safely stops accessing properties if any step is null/undefined:
    console.log(user?.email); // Returns undefined instead of throwing an error
    
  • Add explicit existence checks if you need to support older environments:
    if (user && user.email) {
      console.log(user.email);
    }
    
  • Combine with nullish coalescing (??) to set a fallback value:
    const userEmail = user?.email ?? "no-email@example.com";
    

2. Correctly Capturing Error Status Codes

The issue here is that not all error objects have a statusCode property. That property is typically only attached to HTTP-specific errors (like those from Node.js’s http module or libraries like Axios). If your error is a generic Error instance or a TypeError, err.statusCode will be undefined – which is why your code keeps hitting the else branch.

Let’s break down solutions based on your use case:

Case 1: Using Node.js’s Built-in HTTP/HTTPS Module

For native HTTP requests, the status code lives on the response object, not the error object (errors here are usually network issues like failed connections):

const http = require('http');

http.get('https://example.com/invalid-endpoint', (res) => {
  if (res.statusCode >= 400) {
    console.log(`Error status code: ${res.statusCode}`);
  } else {
    // Handle successful response
  }
}).on('error', (err) => {
  // This is for network errors (no status code here)
  console.log('Network error:', err.message);
});

Case 2: Using an HTTP Client Like Axios

Axios wraps HTTP errors in an object where the status code lives under err.response.status:

try {
  const response = await axios.get('https://example.com/invalid-endpoint');
} catch (err) {
  if (err.response) {
    // Server returned an error response
    console.log('Status code:', err.response.status);
  } else if (err.request) {
    // Request was sent but no response was received
    console.log('No response from server:', err.request);
  } else {
    // Error setting up the request
    console.log('Request setup failed:', err.message);
  }
}

Case 3: Custom Functions Throwing Errors

If you’re writing your own functions, you need to manually attach the statusCode to the error when throwing it:

async function fetchData() {
  try {
    // Simulate a failed operation
    throw new Error('Resource not found');
  } catch (err) {
    // Add status code to the error
    err.statusCode = 404;
    throw err;
  }
}

// When calling the function
try {
  await fetchData();
} catch (err) {
  if (err.statusCode) {
    console.log('Status code:', err.statusCode);
  } else {
    console.log('Generic error:', err.message);
  }
}

Key Takeaway

First, check what type of error you’re dealing with. Log the entire err object to the console (console.log(err)) to see its structure – this will tell you exactly where the status code is stored (if it exists at all).


内容的提问来源于stack exchange,提问作者pavithra prabodha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:18:47