English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Node.js Try Catch

Node.js Try Catch È un meccanismo di gestione degli errori. Quando si aspetta che un segmento di codice generi un errore e venga circondato da try, qualsiasi eccezione lanciata nel segmento di codice può essere risolta nel blocco catch. Se non viene gestito in alcun modo, il programma si interromperà improvvisamente, il che non è una buona cosa.

Attenzione: meglioNode.js Try CatchSolo per operazioni同步e esploreremo anche in questa guida perché non si dovrebbeTry Catchper operazioni asincrone.

  • Esempio di Node.js che tenta di catturare

  • Why not use Node.js Try Catch to catch errors in asynchronous operations

  • Come si comportano le eccezioni nei codici asincroni?

Esempio di Node.js che tenta di catturare

In questo esempio, eseguiremoTentativoCodice intorno alla lettura sincrona del file utilizzatoTry Catch

# Esempio per Try Catch Node.js
var fs = require('fs'); 
 
try{ 
    // File non trovato
    var data = fs.readFileSync('sample.html'); 
 } catch (err) { 
    console.log(err); 
 } 
 
console.log("Continuing with other statements...");

When the above program runs...

Output del terminale

arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-try-catch-example.js  
 { Error: ENOENT: file o directory non trovato, 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' 
Continuando con altre istruzioni...

Attenzione, il programma non si è improvvisamente fermato, ma ha continuato a eseguire le successive istruzioni.

Ora vedremo cosa succede se non si utilizza try catch per la stessa operazione sopra menzionata.

# Errore senza Try Catch Node.js
var fs = require('fs'); 
 
// Tentativo di lettura sincrona del file, invece di presentare il file
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...

Output del terminale

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

Why not use Node.js Try Catch to catch errors in asynchronous operations

Consider the following example, in which we attempt to read a file asynchronously using a callback function and throw an error if a problem occurs. 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', 
        // Funzione di callback
        function(err, data) {  
            if (err) throw err; 
    }); 
 } catch(err){ 
    console.log("Nel blocco Catch") 
    console.log(err); 
 } 
console.log("Dichiarazioni successive")

Output del terminale

arjun@arjun-VPCEH26EN:~/nodejs/try-catch$ node nodejs-try-catch-example-2.js  
Dichiarazioni successive
/home/arjun/nodejs/try-catch/nodejs-try-catch-example-2.js:8
            if (err) throw err; 
                     ^
 
Error: ENOENT: file o directory non trovato, apri 'sample.txta'

Se osservi l'output, per favore eseguiconsole.nelif(err)  lancia  errè stato eseguito primalog("Dichiarazioni successive")  Poiché la lettura del file viene eseguita in modo asincrono e il controllo non aspetta la fine dell'operazione di file, continua a eseguire la dichiarazione next.Questo significa che il controllo non è all'interno del blocco try catch.Se si verifica un errore durante l'operazione asincrona, il controllo non conosce alcun blocco try catch.Quindi, il blocco Try Catch non può catturare gli errori che possono verificarsi durante l'operazione asincrona, e gli sviluppatori dovrebbero evitare di utilizzarloNode.js Try CatchBloccoCatturaErrori generati da compiti asincroni

Come si comportano le eccezioni nei codici asincroni?

Se ti senti confuso su cosa succede con le eccezioni nei codici asincroni, questa è la risposta. Se hai già utilizzato la funzione di callback e hai osservato l'oggetto di errore come parametro, qui riportare tutte le eccezioni o errori al Node.js.

Sommario:

In questa guida Node.js – Try Catch in Node.js,abbiamo imparato a utilizzare Try Catch e le scene in cui non viene utilizzato Try Catch.