繁体   English   中英

启动expressjs服务器时如何抛出错误?

[英]How can I throw an error when starting an expressjs server?

这是我的最小代码示例:

...

const url = typeof process.env.url === 'string' ? process.env.url : {do not start a server}
...
server.start(options, ({ port }) => console.log(`Server is running on http://localhost:${port}`));

如果未设置process.env.url如何抛出错误(或仅打印出一些内容)并避免启动服务器(请参见代码示例)。

您可以简单地抛出错误并退出过程:

function notValid() {
  throw new Error('The passed url is not valid!');
  process.exit()
}

const url = typeof process.env.url === 'string' ? process.env.url : notValid();

server.start(options, ({ port }) => console.log(`Server is running on http://localhost:${port}`));
const url = typeof process.env.url === 'string' ? process.env.url : new Error("Error Message")
if(url instanceof Error) {
  throw url;
}
server.start(options, ({ port }) => console.log(`Server is running on http://localhost:${port}`));

您可以将“ Error Message更改为所需的任何消息,这将破坏服务器(抛出错误)

没有错误

const url = typeof process.env.url === 'string' ? process.env.url : null
if(!url) {
   process.exit(0);
}
server.start(options, ({ port }) => console.log(`Server is running on http://localhost:${port}`));

一个简单的if条件就足够了:

const url = process.env.url || false
if(!url) {
   console.log('error..'); 
   process.exit(0)
}

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM