MST

星途 面试题库

面试题:Node.js中HTTP请求错误捕获基础

在Node.js中使用HTTP模块发起请求时,常见的错误类型有哪些?请至少列举三种,并说明如何使用try - catch块捕获这些错误。
45.9万 热度难度
前端开发Node.js

知识考点

AI 面试

面试题答案

一键面试
  1. 网络连接错误
    • 原因:如目标服务器不可达、网络中断等。
    • 在Node.js中使用http模块发起请求时,若网络连接失败,http.request的回调函数会收到一个error参数。可以在回调函数中捕获,也可以用try - catch块捕获。例如:
    const http = require('http');
    try {
      const req = http.request({
        host: 'nonexistent-server.com',
        port: 80,
        method: 'GET'
      }, (res) => {
        // 处理响应
      });
      req.end();
    } catch (error) {
      console.error('捕获到网络连接错误:', error.message);
    }
    
  2. 超时错误
    • 原因:请求在规定时间内未得到响应。
    • 可以通过设置timeout选项,并结合try - catch块捕获。示例如下:
    const http = require('http');
    try {
      const req = http.request({
        host: 'example.com',
        port: 80,
        method: 'GET',
        timeout: 2000 // 设置2秒超时
      }, (res) => {
        // 处理响应
      });
      req.on('timeout', () => {
        req.abort();
        throw new Error('请求超时');
      });
      req.end();
    } catch (error) {
      console.error('捕获到超时错误:', error.message);
    }
    
  3. 请求格式错误
    • 原因:如错误的HTTP方法、不正确的请求头格式等。
    • 同样可以在http.request的回调函数中捕获错误,也可以利用try - catch块。例如:
    const http = require('http');
    try {
      const req = http.request({
        host: 'example.com',
        port: 80,
        method: 'INVALIDMETHOD' // 错误的HTTP方法
      }, (res) => {
        // 处理响应
      });
      req.end();
    } catch (error) {
      console.error('捕获到请求格式错误:', error.message);
    }