To handle errors thrown by require() module in Node.js, we use a try-catch block.
For instance, we write
let m;
try {
m = require(modulePath);
} catch (e) {
if (e.code !== "MODULE_NOT_FOUND") {
throw e;
}
m = backupModule;
}
to wrap the require
call in a try block.
And then we add a catch block that checks the error code
.
If it’s not 'MODULE_NOT_FOUND'
, then we throw the e
error.
Otherwise, we set m
to backupModule
.