Best practices for Node.js Async Error Handling
.cursorrules in your project root# Node.js Async Error Handling Rules
=====================================
## Core Principles
-----------------
1. **Always handle errors**: Error handling is crucial in asynchronous code to prevent crashes and provide a better user experience.
2. **Use try-catch blocks**: Wrap asynchronous code in try-catch blocks to catch and handle errors.
3. **Handle errors centrally**: Use a central error handling mechanism to handle errors in a consistent manner.
## Code Style Guidelines
-----------------------
### Naming
* Use descriptive variable names for error objects, e.g., `asyncError` instead of `err`.
* Use `error` or `err` as the parameter name for error handling functions.
### Typing
* Use the `Error` type for error objects.
* Use the `Promise` type for asynchronous functions that return promises.
## Best Practices
-----------------
### 1. Use Async/Await
* Use `async/await` syntax for asynchronous code to make it easier to read and maintain.
* Always use `try-catch` blocks with `async/await` to handle errors.
Example:
```javascript
async function example() {
try {
const data = await fetchData();
// Process data
} catch (error) {
// Handle error
}
}
```
### 2. Handle Errors in Callbacks
* Always handle errors in callbacks, even if the error is not expected to occur.
* Use the `error` parameter in callbacks to handle errors.
Example:
```javascript
function example(callback) {
// Asynchronous code
callback(null, data); // or callback(error, null)
}
```
### 3. Use Promise Rejection
* Use promise rejection to handle errors in promise chains.
* Always handle promise rejections using `catch()`.
Example:
```javascript
function example() {
return fetchData()
.then((data) => {
// Process data
})
.catch((error) => {
// Handle error
});
}
```
### 4. Log Errors
* Log errors to track and debug issues.
* Use a logging library or framework to log errors.
Example:
```javascript
const logger = require('logger');
async function example() {
try {
const data = await fetchData();
// Process data
} catch (error) {
logger.error('Error occurred', error);
}
}
```
### 5. Test Error Handling
* Test error handling mechanisms to ensure they work as expected.
* Use testing frameworks to write unit tests for error handling code.
Example:
```javascript
const assert = require('assert');
describe('example', () => {
it('should handle error', async () => {
try {
await example();
assert.fail('Error not thrown');
} catch (error) {
assert.ok(error);
}
});
});
```
## Common Pitfalls to Avoid
---------------------------
### 1. Unhandled Rejections
* Avoid unhandled rejections by always handling promise rejections using `catch()`.
* Use `try-catch` blocks to catch and handle errors in asynchronous code.
### 2. Swallowing Errors
* Avoid swallowing errors by always logging or handling errors.
* Use logging libraries or frameworks to log errors.
### 3. Inconsistent Error Handling
* Avoid inconsistent error handling by using a central error handling mechanism.
* Use a consistent error handling approach throughout the application.
By following these rules, you can ensure that your Node.js application handles asynchronous errors effectively and provides a better user experience.Comprehensive Cursor rules for Next.js 14+ with App Router, including routing, layouts, and API patterns.
Cursor rules for TypeScript with strict type checking, advanced patterns, and best practices.
Cursor rules for Tailwind CSS development with responsive design, custom components, and dark mode.
Cursor
coding
AI coding rules customize how Cursor generates and refactors code for your project. Follow these steps to install Node.js Async Error Handling.
.cursor/rules, for Windsurf use .windsurfrulesComprehensive Cursor rules for Next.js 14+ with App Router, including routing, layouts, and API patterns.
Cursor rules for TypeScript with strict type checking, advanced patterns, and best practices.
Cursor rules for Tailwind CSS development with responsive design, custom components, and dark mode.