I am currently using Babel.
I did the following before with require
:
try {
var myModule = require('my-module');
} catch (err) {
// send error to log file
}
However when trying to do this with import
:
try {
import myModule from 'my-module';
} catch (err) {
// send error to log file
}
I get the error:
'import' and 'export' may only appear at the top level
Now I understand that import
is different to require
. From reading Are ES6 module imports hoisted? import
hoists which means the imports are loaded before code execution.
What I did before was that if any requires failed a log was created which alerted me via email (sending logs to logstash etc.). So my question boils down to the following.
How does one handle import errors in a good practice fashion in nodejs? Does such a thing exist?
You can't catch static imports errors (cf. Boris' answer)
Yet, you could use a dynamic import()
for that.
It's now supported by all evergreen browsers & Node, and is part of the standards since ES2020.
class ImportError extends Error {}
const loadModule = async (modulePath) => {
try {
return await import(modulePath)
} catch (e) {
throw new ImportError(`Unable to import module ${modulePath}`)
}
}
[2021 Edit] Look at Caveman answer for a more up to date answer allowing to make dynamic import
This talk give it away : https://github.com/ModuleLoader/es-module-loader/issues/280 and agree with what you said.
import only works at the base level. They are static and always load before the module is run.
So you can't do a code check.
But, the good news is that as it's static, it can be analysed, tools like webpack throw errors at build time.
Supplementary dynamic import.
class ImportError extends Error {}
const loadModule = async (modulePath) => {
try {
return await import(modulePath)
} catch (e) {
throw new ImportError(`Unable to import module ${modulePath}`)
}
}
async function main() {
// import myDefault, {foo, bar} from '/modules/my-module.js'
const { default: myDefault, foo, bar } = await loadModule('/modules/my-module.js')
}
or chained_promises
import("/modules/my-module.js").then(module=>{
module.foo()
module.bar()
}).catch(err=>
console.log(err.message)
)
or Destructuring assignment
import("/modules/my-module.js").then(({foo, bar})=>{
foo()
bar()
}).catch(err=>
console.log(err.message)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With