English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Try Catch في Node.js 是一种错误处理机制。当期望一段代码抛出错误并被try包围时,可以在catch块中解决代码段中抛出的任何异常。如果未以任何方式处理错误,程序将突然终止,这不是一件好事。
注意:最好将Try Catch في Node.js仅用于同步操作。我们还将在本教程中了解为什么不应该将Try Catch用于异步操作。
Node.js尝试捕获的示例
Why not use Node.js Try Catch to catch errors in asynchronous operations
كيف ستتصرف الاستثنيات في الشيفرة المتزامنة؟
在此示例中,我们将在尝试同步读取文件的代码段周围使用Try Catch。
#example for Node.js Try Catch var fs = require('fs'); try{ // 文件不存在 var data = fs.readFileSync('sample.html'); } catch (err){ console.log(خطأ); } console.log("Continuing with other statements...");
When the above program runs...
الخروج من الطرفية
arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-try-catch-example.js { Error: ENOENT: no such file or directory, open 'sample.html' at Object.fs.openSync (fs.js:652:18) at Object.fs.readFileSync (fs.js:553:33) at Object.<anonymous> (/nodejs/nodejs-try-catch-example.js:5:16) at Module._compile (module.js:573:30) at Object.Module._extensions..js (module.js:584:10) at Module.load (module.js:507:32) at tryModuleLoad (module.js:470:12) at Function.Module._load (module.js:462:3) at Function.Module.runMain (module.js:609:10) at startup (bootstrap_node.js:158:16) errno: -2, code: 'ENOENT', syscall: 'open', path: 'sample.html'} Continuing with other statements..
请注意,该程序并没有突然终止,而是继续执行后续语句。
现在,我们将看到如果不对上面的同一操作使用try catch,将会发生什么。
# error without Node.js Try Catch var fs = require('fs'); // 尝试同步读取文件,而不是presenet文件 var data = fs.readFileSync('sample.html'); console.log("Continuing with other statements...");
There is no error handling mechanism in the code. And the program terminates abruptly, and the subsequent statements do not execute.
When the above program runs...
الخروج من الطرفية
arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-try-catch-example-1.js /home/arjun/nodejs/nodejs-try-catch-example-1.js:1 (function (exports, require, module, __filename, __dirname) { # example for Node.js Try Catch ^ SyntaxError: Invalid or unexpected token at createScript (vm.js:74:10) at Object.runInThisContext (vm.js:116:10) at Module._compile (module.js:537:28) at Object.Module._extensions..js (module.js:584:10) at Module.load (module.js:507:32) at tryModuleLoad (module.js:470:12) at Function.Module._load (module.js:462:3) at Function.Module.runMain (module.js:609:10) at startup (bootstrap_node.js:158:16) at bootstrap_node.js:598:3
Consider the following example, in which we attempt to read a file asynchronously using a callback function and throw an error if there is a problem. Then, we wrap the task with a 'try-catch' block, hoping to catch the thrown error.
# Node.js Try Catch with Asynchronous Callback Function var fs = require('fs'); try{ fs.readFile('sample.txta', // دالة الاستدعاء function (خطأ، بيانات) { if (خطأ) throw خطأ; }); } console.log("في كتلة التقاطع") console.log(خطأ); } console.log("جملة التالي")
الخروج من الطرفية
arjun@arjun-VPCEH26EN:~/nodejs/try-catch$ node nodejs-try-catch-example-2.js جملة التالي /home/arjun/nodejs/try-catch/nodejs-try-catch-example-2.js:8 if (خطأ) throw خطأ; ^ خطأ: ENOENT: لا يوجد ملف أو مجلد، فتح 'sample.txta'
إذا لاحظت الخروج، قم بالشاشة.فيif(خطأ) throw خطأتم تنفيذها مسبقًاlog("جملة التالي") ، لأن قراءة الملف تتم بشكل متزامن، و لا ينتظر التحكم إنهاء عملية التشغيل، بل يستمر في تنفيذ جملة التالي.إذا كان هذا يعني أن التحكم ليس داخل كتلة try catch.إذا حدث خطأ أثناء عملية التشغيل المتزامنة، لن يعرف التحكم أي كتلة try catch.لذلك، لا يمكن التقاطع بالكتلة Try Catch لأي أخطاء قد تحدث أثناء عملية التشغيل المتزامنة، ويجب على المطورين تجنب استخدامهاTry Catch في Node.jsالكتلةالتقاطعال أخطاء التي تُطلق عن طريق المهام المتزامنة。
إذا كنت تشعر بالحيرة حول ما سيحدث لاستثنيات الشيفرة المتزامنة، فهذا هو الجواب. إذا قمت بالفعل بتشغيل الدالة الاستدعاء Callback و لاحظت أن obj الخطأ يتم تقديمه كمعامل، فسيتم إعادة تقرير جميع الأخطاء أو الاستثنيات إلى Node.js هنا.
في هذا الدليل لـ Node.js – في Try Catch لـ Node.js،لقد تعلمنا استخدام Try Catch وأيضًا السيناريوهات التي لا تستخدم Try Catch.