0 day streak
javascript / beginner
Snippet

Basic Error Handling

The try...catch block prevents your Node.js application from crashing when an error occurs. The 'try' block contains risky code, and 'catch' handles the error if one happens.

snippet.js
javascript
1
2
3
4
5
try {
const data = JSON.parse('invalid json');
} catch (error) {
console.error('An error occurred:', error.message);
}
nodejs
Breakdown
1
try {
Starts a block of code to monitor for errors.
2
} catch (error) {
Executes this block if an error was thrown in the try block.