[英]How can I throw an error when starting an expressjs server?
Here's my minimal code example: 这是我的最小代码示例:
...
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}`));
How can I throw an error (or just print out something) and avoid starting a server if process.env.url
is not set (please see the code sample). 如果未设置process.env.url
如何抛出错误(或仅打印出一些内容)并避免启动服务器(请参见代码示例)。
You can simply throw the error and exit the process: 您可以简单地抛出错误并退出过程:
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}`));
You can change Error Message
to any message you want and that will break the server (with error thrown) 您可以将“ 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}`));
A simple if condition would suffice: 一个简单的if条件就足够了:
const url = process.env.url || false
if(!url) {
console.log('error..');
process.exit(0)
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.