【问题标题】:HTTP server error handler in Typescript and Node.jsTypescript 和 Node.js 中的 HTTP 服务器错误处理程序
【发布时间】:2020-02-26 02:13:36
【问题描述】:

我正在为我的后端代码库转换 Typescript,但是在收听 http 服务器 Error Event 时,我遇到了关于 [ts] property syscall does not exist on error 的问题。我认为这里的 Error 类型是错误的,但是显然 Node.js 没有为这个回调函数提供默认的错误类型。任何人都可以帮助我正确的错误类型吗?

const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.write('Hello World!');
  res.end();
})

server.listen(3000);
server.on('error', onError);

function onError(error: Error) {
  // [ts] property syscall does not exist on error
  if (error.syscall !== 'listen') {
    throw error;
  }
}

【问题讨论】:

    标签: node.js typescript


    【解决方案1】:

    尝试将 error 变量的类型从 Error 更改为 NodeJS.ErrnoException。此类型是一个扩展基本Error 接口并添加syscall 属性等的接口。

    来源:https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/index.d.ts#L401

    export interface ErrnoException extends Error {
        errno?: number;
        code?: string;
        path?: string;
        syscall?: string;
        stack?: string;
    }
    

    【讨论】:

      【解决方案2】:

      如果您使用类型,例如@types/node,则您要使用的类是NodeJS.ErrnoException。说用any来解决缺类型的问题,就等于说如果你想在汽车上停止爆胎,把轮子取下来。

      【讨论】:

        【解决方案3】:

        这是因为不是每个 Error 对象都需要有一个系统调用属性。

        你也许可以通过改变这个来修复它:

        function onError(error: Error) {
          // [ts] property syscall does not exist on error
          if (error.syscall !== 'listen') {
            throw error;
          }
        }
        

        到这里:

        function onError(error: any) {
          if (error.syscall !== 'listen') {
            throw error;
          }
        }
        

        有关一些背景信息,请参阅此问题 cmets:

        【讨论】:

        • 是的。这正是我想说的。我虽然 @types/node 已经有了这个回调的内置类型。但我仍然想使用静态检查而不是使用任何
        • 绝对错误的做法,你只是放弃使用类型。
        猜你喜欢
        • 1970-01-01
        • 2016-01-28
        • 1970-01-01
        • 2018-01-09
        • 2016-10-25
        • 2014-03-24
        • 2016-06-12
        • 2021-04-07
        • 1970-01-01
        相关资源
        最近更新 更多