简体   繁体   English

的NodeJS。 我可以在一个地方处理错误吗? 没有尝试抓住块

[英]NodeJS. Can I handle errors in one place? Without try and catch blocks

Node said that I should catch errors on all my promises. Node表示我应该兑现所有诺言。

Does exist a good practice for handling the same errors in one function? 是否存在在一个函数中处理相同错误的良好实践? I don't want to write always the same catch block for all requests. 我不想为所有请求编写始终相同的catch块。

My code looks like: 我的代码如下:

(async () => {
  try {
    await makeRequest()    
  }
  catch(e) {
    console.error(e)
  }
})()

Try this : 尝试这个 :

makeRequest()
    .catch(err => {
        // console.error(err)
    })

For async IIFE (IIAFE) error handling is performed as: 对于async IIFE(IIAFE),错误处理如下:

(async () => {
  await makeRequest()    
})().catch(console.error);

Notice that in Node.js console methods are bound to proper context, so they can be passed as callbacks. 请注意,在Node.js中, console方法绑定到适当的上下文,因此可以将它们作为回调传递。

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

相关问题 如何在不使用控制器中的 try 和 catch 的情况下全局处理 express 中的错误 - how can I handle errors in express globally without using try and catch in my controllers 如何在不使用 try catch 块的情况下处理多个 async await whle promise 中的错误? - how to handle errors in multiple async await whle promise rejected without using try catch blocks? 在(嵌套)try/catch/finally 块中处理 nodejs 中的错误 - Handling errors in nodejs in (nested) try/catch/finally blocks 我如何处理在 javascript/nodejs 中的 catch 块中发生的错误 - How do I handle errors that occure in the catch block in javascript/nodejs 无法安装最新版本的 nodejs。 我尝试安装 nodejs 17.x - Unable to install latest version of nodejs. I try to install nodejs 17.x 每当我尝试使用 NPM 或 nodejs 时,都会出现分段错误。 卸载并重新安装并不能解决它 - I get segmentation fault whenever I try to use NPM or nodejs. Uninstalling and reinstalling doesn't fix it 如何在一个地方处理所有错误? - How should I handle all my errors in one place? 的NodeJS。 没有表格上传文件 - nodejs. Upload File without a form 我如何不进行尝试就测试错误处理-catch - How can I test error handing without try— catch 在不重复代码的情况下处理/捕获错误? - Handle/catch errors without repeating code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM