Skip to content

Commit 64888a1

Browse files
committed
docs: revised the readme for better clarity and examples
1 parent 59bcf57 commit 64888a1

File tree

2 files changed

+94
-36
lines changed

2 files changed

+94
-36
lines changed

README.md

Lines changed: 93 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
![Build Status](https://img.shields.io/github/workflow/status/riyons/nextjs-centralized-error-handler/Publish%20Package)
99
![Test Coverage](https://img.shields.io/coveralls/github/riyons/nextjs-centralized-error-handler)
1010

11-
**A comprehensive, secure error-handling package designed specifically for Next.js applications.** While Next.js 13 provides global middleware for high-level request interception, `nextjs-centralized-error-handler` enables **fine-grained, route-level error handling** with custom error classes, ensuring that error responses are both consistent and structured. The package simplifies error handling by removing the need for repetitive `try-catch` blocks, enhancing security by preventing sensitive data leakage, and making error responses frontend-compatible. Fully compatible with Next.js 13 and above.
11+
**A comprehensive, secure error-handling package designed specifically for Next.js applications.** While Next.js 13 provides global middleware for high-level request interception, `nextjs-centralized-error-handler` enables **fine-grained, route-level error handling** with `custom error classes`, ensuring that error responses are both consistent and structured. The package simplifies error handling by removing the need for repetitive `try-catch` blocks, enhancing security by preventing sensitive data leakage, and making error responses frontend-compatible. Fully compatible with Next.js 13 and above.
1212

1313
## Table of Contents
1414

@@ -104,7 +104,7 @@ Next.js 13’s middleware offers powerful global interception capabilities, idea
104104
105105
1. **Route-Specific Error Management**: With `nextjs-centralized-error-handler`, each route can define its own contextual error handling, with tailored messages that match the route’s functionality. This modularity is essential for complex applications with varied error handling needs across different endpoints.
106106
107-
2. **Custom Error Classes with Detailed Responses**: The package introduces custom error classes (e.g., `BadRequestError`, `UnauthorizedError`) with structured, frontend-friendly JSON responses. These responses are enriched with metadata like status codes and error types, ensuring predictable and standardized error handling for backend and frontend teams.
107+
2. **Custom Error Classes with Detailed Responses**: The package introduces `custom error classes` (e.g., `BadRequestError`, `UnauthorizedError`) with structured, frontend-friendly JSON responses. These responses are enriched with metadata like status codes and error types, ensuring predictable and standardized error handling for backend and frontend teams.
108108
109109
3. **Enhanced Security and Data Privacy**: Only errors that are intentional instances of `CustomError` have their status codes and messages sent to the client. For unexpected errors, a generic error message is used, and sensitive details are kept server-side, minimizing information leakage.
110110
@@ -145,42 +145,106 @@ export const config = {
145145
146146
### Comparison with nextjs-centralized-error-handler
147147
148-
While Next.js middleware is useful for global, high-level tasks, nextjs-centralized-error-handler enables route-specific error handling with custom error classes for fine-grained control. Here’s how both work together:
148+
While Next.js middleware is useful for global, high-level tasks, `nextjs-centralized-error-handler` enables route-specific error handling with `custom error classes` for fine-grained control. Here’s how both work together:
149149
150-
| Feature | Next.js 13 Middleware | nextjs-centralized-error-handler |
151-
|-----------------------------|------------------------------------------------|----------------------------------------------------------|
152-
| Scope | Global, based on route pattern matching | Route-specific, applied individually to each handler |
153-
| Use Case | Authentication, global request validation | Detailed error handling, custom error messages |
154-
| Custom Error Responses | Limited, generalized JSON responses | Structured, frontend-compatible JSON responses |
155-
| Custom Error Classes | | |
156-
| Error Logging Integration | | ✅ (supports Sentry, Datadog, etc.) |
157-
| Fine-Grained Control | | |
150+
| Feature | Next.js 13 Middleware | nextjs-centralized-error-handler |
151+
|---------------------------|----------------------------------|----------------------------------------------------|
152+
| Scope | Global, based on route pattern matching | Route-specific, applied individually to each handler |
153+
| Use Case | Authentication, global request validation | Detailed error handling, custom error messages |
154+
| Custom Error Responses | Limited, generalized JSON responses | Structured, frontend-compatible JSON responses |
155+
| Custom Error Classes |||
156+
| Error Logging Integration || ✅ (supports Sentry, Datadog, etc.) |
157+
| Fine-Grained Control |||
158158
| Preventing Information Leakage | Limited, as it handles errors globally without distinguishing between error types | Enhanced, distinguishes between custom and unexpected errors to prevent sensitive data exposure |
159159
| Integration with Route Handlers | Middleware runs before route handlers, cannot modify responses within handlers | Wraps individual route handlers, allowing for customized responses per route |
160-
| Extensibility | Limited to what middleware can handle globally | Highly extensible through custom error classes and configurable options |
160+
| Extensibility | Limited to what middleware can handle globally | Highly extensible through `custom error classes` and configurable options |
161161
162-
### Why Use Both Approaches Together
162+
### Understanding Scope and Flexibility: Next.js Middleware vs. `nextjs-centralized-error-handler`
163163
164-
Combining both Next.js middleware and nextjs-centralized-error-handler provides a comprehensive error-handling strategy:
164+
While Next.js middleware provides a powerful mechanism for high-level request interception, `nextjs-centralized-error-handler` excels at fine-grained error handling within individual API routes. This section clarifies their distinct roles and how they can be used together effectively.
165165
166-
**Global Request Validation and Authentication:**
166+
#### Scenario: User Input Validation
167167
168-
- Use Next.js middleware to handle tasks that need to be applied across multiple routes, such as authentication, authorization, and general request validation.
168+
Imagine you are building an API route that requires a user's name to be provided in the request body. If the name is missing, you want to respond with a clear and specific error message. Let's see how each approach handles this scenario.
169169
170-
**Route-Specific Detailed Error Handling:**
170+
##### Using Next.js Middleware
171171
172-
- Use nextjs-centralized-error-handler to manage errors that occur within individual route handlers, allowing for customized and structured error responses tailored to each route's specific needs.
172+
In Next.js, middleware can be used to validate requests globally. However, it cannot catch exceptions thrown within individual route handlers.
173173
174-
### Example: Using Both Middleware and nextjs-centralized-error-handler
174+
```javascript
175+
// middleware.js
176+
import { NextResponse } from 'next/server';
177+
178+
export function middleware(req) {
179+
try {
180+
// You can include any logic here that might throw an error
181+
return NextResponse.next(); // Proceed to the route handler
182+
} catch (error) {
183+
// Handle the error and return an appropriate response
184+
return NextResponse.json({ error: 'An error occurred while processing your request.' }, { status: 500 });
185+
}
186+
}
187+
```
188+
```javascript
189+
// pages/api/example.js
190+
const handler = async (req, res) => {
191+
if (!req.body.name) {
192+
throw new Error('Name is required.'); // This will not be caught by middleware
193+
}
194+
195+
res.status(200).json({ message: `Hello, ${req.body.name}!` });
196+
};
197+
198+
export default handler;
199+
```
200+
201+
**What Happens Here:**
202+
203+
1. The middleware runs before the route handler to process the request.
204+
2. If `req.body.name` is missing, the `Error` is thrown.
205+
3. However, the middleware will not catch this error, resulting in a generic 500 Internal Server Error.
206+
207+
##### Using nextjs-centralized-error-handler
175208
176-
#### Middleware (middleware.js):
209+
In contrast, `nextjs-centralized-error-handler` provides a higher-order function that captures errors thrown in route handlers.
210+
211+
```javascript
212+
// pages/api/example.js
213+
import { errorHandler, BadRequestError } from 'nextjs-centralized-error-handler';
214+
215+
const handler = async (req, res) => {
216+
if (!req.body.name) {
217+
throw new BadRequestError('Name is required.'); // This will be caught by errorHandler
218+
}
219+
220+
res.status(200).json({ message: `Hello, ${req.body.name}!` });
221+
};
222+
223+
export default errorHandler(handler);
224+
```
225+
226+
**What Happens Here:**
227+
228+
1. The `errorHandler` wraps the route handler, intercepting any errors thrown within it.
229+
2. If `req.body.name` is missing, the `BadRequestError` is thrown and caught by `errorHandler`.
230+
3. This results in a structured response with the appropriate status code (400) and a clear error message ("Name is required.").
231+
232+
#### Why Use Both Approaches Together
233+
234+
Combining both Next.js middleware and `nextjs-centralized-error-handler` provides a comprehensive error-handling strategy:
235+
236+
- **Global Request Validation and Authentication:** Use Next.js middleware to handle tasks that need to be applied across multiple routes, such as authentication, authorization, and general request validation.
237+
- **Route-Specific Detailed Error Handling:** Use `nextjs-centralized-error-handler` to manage errors that occur within individual route handlers, allowing for customized and structured error responses tailored to each route's specific needs.
238+
239+
##### Example: Using Both Middleware and `nextjs-centralized-error-handler`
240+
241+
**Middleware (middleware.js):**
177242
178243
```javascript
179244
// middleware.js (Next.js Middleware for global authentication)
180245
import { NextResponse } from 'next/server';
181246
182247
export function middleware(req) {
183-
// Example of authentication
184248
if (!req.headers.get('Authorization')) {
185249
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
186250
}
@@ -193,7 +257,7 @@ export const config = {
193257
};
194258
```
195259
196-
#### Route Handler (pages/api/example.js):
260+
**Route Handler (pages/api/example.js):**
197261
198262
```javascript
199263
// pages/api/example.js (Using nextjs-centralized-error-handler for route-specific errors)
@@ -204,22 +268,16 @@ const handler = async (req, res) => {
204268
throw new BadRequestError('Name is required.');
205269
}
206270
207-
// POST request handling logic
208271
res.status(200).json({ message: 'Success' });
209272
};
210273
211274
export default errorHandler(handler);
212275
```
213276
214-
### Explanation:
215-
216-
- **Middleware (middleware.js):**
217-
- Handles global tasks like authentication.
218-
- Applies to all `/api/*` routes based on the matcher configuration.
277+
**Explanation:**
219278
220-
- **Route Handler (example.js):**
221-
- Handles route-specific logic.
222-
- Utilizes `nextjs-centralized-error-handler` for detailed error handling and structured responses.
279+
- **Middleware (middleware.js):** Handles global tasks like authentication. Applies to all `/api/*` routes based on the matcher configuration.
280+
- **Route Handler (example.js):** Handles route-specific logic. Utilizes `nextjs-centralized-error-handler` for detailed error handling and structured responses.
223281
224282
By using Next.js middleware for request-level checks and `nextjs-centralized-error-handler` for response-level error handling, you achieve both broad validation and fine-grained error management.
225283
@@ -280,7 +338,7 @@ const handler = async (req, res) => {
280338
281339
export default errorHandler(handler);
282340
```
283-
With `nextjs-centralized-error-handler`, you avoid repetitive error-handling code in each route. Instead, custom error classes and the `errorHandler` higher-order function provide centralized, consistent error responses, simplifying maintenance and extending error handling across the entire application.
341+
With `nextjs-centralized-error-handler`, you avoid repetitive error-handling code in each route. Instead, `custom error classes` and the `errorHandler` higher-order function provide centralized, consistent error responses, simplifying maintenance and extending error handling across the entire application.
284342
285343
---
286344
@@ -328,7 +386,7 @@ yarn add nextjs-centralized-error-handler
328386
329387
### Basic Setup
330388
331-
Import `errorHandler` and custom error classes into your Next.js API route:
389+
Import `errorHandler` and `custom error classes` into your Next.js API route:
332390
333391
```javascript
334392
// pages/api/someEndpoint.js
@@ -348,7 +406,7 @@ export default errorHandler(handler);
348406
349407
### Custom Error Classes
350408
351-
The package includes several predefined error classes:
409+
The package includes several predefined `error classes`:
352410
353411
- `BadRequestError` (400)
354412
- `UnauthorizedError` (401)
@@ -385,7 +443,7 @@ throw new ForbiddenError("Custom forbidden message."); // Uses custom message pr
385443
386444
#### Creating Custom Errors
387445
388-
To address specific needs beyond predefined classes, the package is designed to be extensible, allowing you to create unique custom errors for advanced use cases. You can extend the base CustomError class to define your own error types, tailored to specific business logic. Here are some examples of custom errors you might create:
446+
To address specific needs beyond predefined classes, the package is designed to be extensible, allowing you to create unique custom errors for advanced use cases. You can extend the base `CustomError class` to define your own error types, tailored to specific business logic. Here are some examples of custom errors you might create:
389447
390448
- `HTTPVersionNotSupportedError` (505)
391449
- `NotImplementedError` (501)

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "nextjs-centralized-error-handler",
3-
"version": "1.0.4",
3+
"version": "1.0.5",
44
"main": "index.js",
55
"scripts": {
66
"test": "jest",

0 commit comments

Comments
 (0)