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).
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)
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:
const url = process.env.url || false
if(!url) {
console.log('error..');
process.exit(0)
}
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.