简体   繁体   中英

NodeJS/mssql error handling differences

I just started using the mssql package to query my DB from NodeJS. My question is about error handling... For starters, here are my module imports:

const sql = require('mssql');
const config = require('./pathToMyConfig.js');

I can see that most methods exposed by the module can be handled as a Promise, and .catch() can be used to handle errors.

sql.connect(config).query("SELECT * FROM Customers").then().catch(err => {...});

But I can also see in the documentation that some times they call .on('error') on the imported mssql module.

sql.connect(config).query().then();
sql.on('error', err => {...});

What's the difference between the 2? I suppose the .catch handles only errors on that Promise body, while .on('error') handles everything that was not caught?

Are there any other differences, or perhaps a convention regarding this?

sql.on('error', err => {...}); will be called if an error occurred while initializing the connection. This allows you to handle any exceptions during initialization.

.catch(err => {...}) is used capture any error that occurred during the execution of the query.

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.

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