简体   繁体   English

NodeJS / mssql错误处理差异

[英]NodeJS/mssql error handling differences

I just started using the mssql package to query my DB from NodeJS. 我刚刚开始使用mssql包从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. 我可以看到该模块公开的大多数方法都可以作为Promise处理, .catch()可用于处理错误。

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. 但是我也可以在文档中看到,有时它们在导入的mssql模块上调用.on('error')

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

What's the difference between the 2? 2和有什么区别? I suppose the .catch handles only errors on that Promise body, while .on('error') handles everything that was not caught? 我想.catch只处理该Promise主体上.on('error') ,而.on('error')处理所有未被捕获.on('error')

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. .catch(err => {...})用于捕获执行查询期间发生的任何错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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