~2 دقیقه مطالعه • بروزرسانی ۶ دی ۱۴۰۴
1. Categories of Errors
- Standard JavaScript Errors:
SyntaxError,ReferenceError,TypeError, etc. - DOMExceptions: Standard browser exceptions.
- System Errors: Triggered by OS constraints (e.g., opening a non-existent file).
- AssertionError: Raised by the
assertmodule when logic violations occur. - User-defined Errors: Errors explicitly thrown in application code.
2. Error Propagation and Handling
Error handling depends on the API style:
- Synchronous APIs: Use
throwand must be handled withtry...catch. - Promise-based APIs: Errors are reported via
rejectand handled withcatch. - Callback-based APIs: Errors are passed as the first argument to the callback.
- EventEmitter APIs: Errors are emitted via the
'error'event.
3. Examples
// Synchronous
try {
const m = 1;
const n = m + z; // ReferenceError
} catch (err) {
console.error(err);
}
// Asynchronous with Promise
const fs = require('node:fs/promises');
(async () => {
try {
await fs.readFile('file.txt');
} catch (err) {
console.error('Error reading file!', err);
}
})();
// Asynchronous with Callback
const fs = require('node:fs');
fs.readFile('file.txt', (err, data) => {
if (err) {
console.error('Error reading file!', err);
return;
}
});
4. Error Class Properties
error.message: Text description of the error.error.code: Stable identifier for the error type.error.stack: Stack trace showing where the error was created.error.cause: Underlying cause of the error (since v16.9.0).
5. Important Error Types
- AssertionError: Indicates assertion failure.
- RangeError: Argument outside valid range.
- ReferenceError: Accessing an undefined variable.
- SyntaxError: Invalid JavaScript code.
- SystemError: Errors caused by OS-level constraints.
Conclusion
Proper error handling in Node.js is critical for building stable applications. Developers must understand the different error categories and propagation mechanisms, and use tools like try...catch, Promise.catch, and 'error' events in EventEmitters to handle errors effectively.
نوشته و پژوهش شده توسط دکتر شاهین صیامی