Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP server error handler in Typescript and Node.js

I'm transforming Typescript for my backend codebase, but when listening to http server Error Event, I'm facing an issue about [ts] property syscall does not exist on error. I think the Error type is wrong here, but apparently Node.js does not provide the default error type for this callback function. Anyone can help me with the correct Error type?

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;
  }
}
like image 595
yue you Avatar asked Feb 09 '18 16:02

yue you


People also ask

What is HTTP createServer in node JS?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.

Is NodeJS an HTTP server?

Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.


2 Answers

Trying changing the type of your error variable from Error to NodeJS.ErrnoException. This type is an interface that extends the base Error interface and adds the syscall property, among others.

Source: 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;
}
like image 135
Nathan Friend Avatar answered Oct 18 '22 21:10

Nathan Friend


If you're using types, like @types/node, the class you want to use is NodeJS.ErrnoException. Saying use any to solve the problem of lacking a type, is the same as saying if you want to stop punctures on a car, take off the wheels.

like image 21
user-12410035 Avatar answered Oct 18 '22 19:10

user-12410035