Skip to content

Commit d6d36b9

Browse files
committed
fix(errorHandler): prevent crash when logger is undefined
- Added validation to ensure the `logger` option is a function before invoking it. - Enhanced the test suite with additional test cases covering scenarios with and without a custom logger. - Improved code comments and documentation for better clarity and maintainability.
1 parent da8100a commit d6d36b9

File tree

7 files changed

+699
-57
lines changed

7 files changed

+699
-57
lines changed

CHANGELOG.md

Lines changed: 37 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,48 @@ All notable changes to this project will be documented in this file.
55

66
The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
77

8-
## [1.0.0] - 2024-10-29
9-
### Added
10-
- Initial release of the package.
11-
- Implemented centralized error handling using higher-order functions.
12-
- Added custom error classes: `BadRequestError`, `UnauthorizedError`, `ForbiddenError`, `NotFoundError`, `InternalServerError`, and `MethodNotAllowedError`.
13-
- Enabled JSON serialization for frontend-compatible error responses.
14-
- Added support for logging services like Sentry.
8+
## [1.0.17] - 2024-11-01
159

16-
## [1.0.1] - 2024-10-29
1710
### Added
18-
- Option to customize error responses using `formatError`.
19-
- Improved error handling for unsupported HTTP methods.
20-
- Expanded documentation in the README.
2111

22-
## [1.0.9] - 2024-10-30
12+
- **Enhanced Test Suite:**
13+
- Expanded the test suite with additional test cases covering more scenarios for both **API Routes** and **App Router** contexts.
14+
- Introduced new custom error classes (e.g., `NotFoundError`) to handle a broader range of HTTP errors.
15+
16+
- **Documentation Improvements:**
17+
- Enhanced code comments and documentation across the codebase for better clarity and maintainability.
18+
2319
### Fixed
24-
- Enhanced the `errorHandler` function to support both API Routes and App Router in Next.js, allowing for flexible error handling across different route types.
25-
- Adjusted error response handling to ensure appropriate responses are returned based on the presence of `res` in the request.
20+
21+
- **Application Stability:**
22+
- Resolved a critical issue where the application would crash if the `logger` function was undefined. Implemented proper validation and fallback mechanisms in the `errorHandler` to ensure graceful error handling even when optional configurations are missing or incorrect.
23+
24+
### Changed
25+
26+
- **Error Handling Logic:**
27+
- Improved the `errorHandler` implementation to better differentiate between **API Routes** and **App Router** contexts, ensuring appropriate response structures and status codes.
28+
- Updated the `errorHandler` to safely invoke custom logging and formatting functions, preventing potential crashes from malformed user-provided functions.
2629

2730
## [1.0.10] - 2024-10-30
2831
### Fixed
2932
- Corrected log message for errors in API Route handling to reflect 'API Route Error:' instead of 'Route Error:' in the logger.
30-
- Ensured consistent error handling for both API Routes and App Router by refining the errorHandler implementation.
33+
- Ensured consistent error handling for both API Routes and App Router by refining the errorHandler implementation.
34+
35+
## [1.0.9] - 2024-10-30
36+
### Fixed
37+
- Enhanced the `errorHandler` function to support both API Routes and App Router in Next.js, allowing for flexible error handling across different route types.
38+
- Adjusted error response handling to ensure appropriate responses are returned based on the presence of `res` in the request.
39+
40+
## [1.0.1] - 2024-10-29
41+
### Added
42+
- Option to customize error responses using `formatError`.
43+
- Improved error handling for unsupported HTTP methods.
44+
- Expanded documentation in the README.
45+
46+
## [1.0.0] - 2024-10-29
47+
### Added
48+
- Initial release of the package.
49+
- Implemented centralized error handling using higher-order functions.
50+
- Added custom error classes: `BadRequestError`, `UnauthorizedError`, `ForbiddenError`, `NotFoundError`, `InternalServerError`, and `MethodNotAllowedError`.
51+
- Enabled JSON serialization for frontend-compatible error responses.
52+
- Added support for logging services like Sentry.

README.md

Lines changed: 46 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
Inspired by my experiences with the Yii2 framework—where built-in error classes allow developers to manage error handling efficiently without hardcoding status codes or messages—I saw a need for similar functionality in the Node.js ecosystem. This led to the development of custom error classes in this package, enhancing consistency and usability.
1313

14-
**Note:** This package is currently in beta. As this package is newly released, your feedback is crucial for identifying any potential issues and improving its stability. I encourage you to try out the `nextjs-centralized-error-handler` package and share your experiences, whether through bug reports or suggestions for improvement. Together, we can enhance this package for the Next.js community.
14+
> **_Important Note:_** This package is currently in beta. As this package is newly released, your feedback is crucial for identifying any potential issues and improving its stability. I encourage you to try out the `nextjs-centralized-error-handler` package and share your experiences, whether through bug reports or suggestions for improvement. Together, we can enhance this package for the Next.js community.
1515
1616
## Table of Contents
1717

@@ -33,6 +33,7 @@ Inspired by my experiences with the Yii2 framework—where built-in error classe
3333
- [Example Usage with Default Messages](#example-usage-with-default-messages)
3434
- [Creating Custom Errors](#creating-custom-errors)
3535
- [Using `nextjs-centralized-error-handler` with App Router](#using-nextjs-centralized-error-handler-with-app-router)
36+
- [Testing](#testing)
3637
- [Customizing Error Handling Behavior](#customizing-error-handling-behavior)
3738
- [Error Handler Options](#error-handler-options)
3839
- [Customizing Error Responses](#customizing-error-responses)
@@ -528,6 +529,48 @@ Using the App Router allows for a clean and structured way to manage errors whil
528529
529530
---
530531
532+
## Testing
533+
534+
Ensuring the reliability and security of the `errorHandler` is paramount. A comprehensive test suite has been implemented to cover various scenarios, guaranteeing that the error handler functions as intended across different contexts and use cases.
535+
536+
### Testing Strategy
537+
538+
- **Isolation**: Each test case is designed to be independent, ensuring that the outcome of one test does not affect others.
539+
- **Coverage**: Tests cover both **API Routes** and **App Router** contexts, handling both custom-defined errors and unexpected runtime errors.
540+
- **Mocking**: Utilizes Jest's mocking capabilities to simulate different environments and behaviors, such as custom loggers and formatters.
541+
- **Edge Cases**: Includes tests for scenarios like throwing non-error objects and invalid `formatError` functions to ensure robustness.
542+
- **Security Assurance**: Verifies that sensitive information is not leaked through error responses.
543+
544+
### Test Cases
545+
546+
| **Test Case** | **Description** | **Context** |
547+
|---------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------|---------------------------|
548+
| **Handle Custom Errors Correctly (API Routes)** | Verifies that custom errors (e.g., `BadRequestError`) are handled with the correct status code and error response structure. | API Routes |
549+
| **Handle Unexpected Errors with Default Status (API Routes)** | Ensures that unexpected errors default to a `500` status code and a generic error message, preventing information leakage. | API Routes |
550+
| **Use Custom `formatError` Function (API Routes)** | Checks that the `formatError` function customizes the error response as expected in API Routes. | API Routes |
551+
| **Use Custom Logger Function (API Routes)** | Confirms that a custom logger function is invoked when an error occurs in API Routes. | API Routes |
552+
| **Handle Custom Errors Correctly (App Router)** | Verifies that custom errors are handled with the correct status code and error response structure in the App Router. | App Router |
553+
| **Handle Unexpected Errors with Default Status (App Router)** | Ensures that unexpected errors default to a `500` status code and a generic error message in the App Router. | App Router |
554+
| **Use Custom `formatError` Function (App Router)** | Checks that the `formatError` function customizes the error response as expected in the App Router. | App Router |
555+
| **Return 204 No Content if Handler Returns Undefined (App Router)** | Ensures that if the handler does not return a response, a `204 No Content` response is sent by default in the App Router. | App Router |
556+
| **Handle Different Custom Errors Correctly** | Tests handling of various custom errors (e.g., `NotFoundError`) with their respective status codes and messages. | API Routes |
557+
| **Use Custom Logger Function (App Router)** | Confirms that a custom logger function is invoked when an error occurs in the App Router. | App Router |
558+
| **Set Content-Type to application/json (App Router)** | Verifies that the `Content-Type` header is correctly set to `application/json` for JSON responses in the App Router. | App Router |
559+
| **Handle Non-Error Objects Gracefully** | Ensures that throwing non-Error objects does not crash the application and defaults to a `500` status with a generic message.| API Routes |
560+
| **Ignore Additional Properties in Errors** | Confirms that additional properties in error objects do not affect the error response structure. | API Routes |
561+
| **Fallback to Default Error Response if `formatError` is Invalid** | Ensures that if `formatError` is not a function or throws an error, the handler defaults to the standard error response. | API Routes & App Router |
562+
563+
### Running Tests
564+
565+
To execute the test suite, ensure you have all dependencies installed and run the following command:
566+
567+
```bash
568+
npm test
569+
```
570+
This command will run all tests using Jest, providing a summary of passed and failed test cases along with coverage information.
571+
572+
---
573+
531574
## Customizing Error Handling Behavior
532575
Beyond custom errors, this package allows developers to fully control the behavior of error handling by:
533576
@@ -804,9 +847,9 @@ This setup captures errors for monitoring, while safeguarding against exposing s
804847
---
805848
806849
## Community Feedback and Stability
807-
As this package is newly released, I am aware of the importance of stability in production environments. While I have conducted testing, the real-world usage and feedback from the community are crucial for identifying any potential issues and improving the package further.
850+
As this package is newly released, I recognize the importance of stability in production environments. While I have conducted testing, real-world usage and feedback from the community are crucial for identifying any potential issues and further improving the package.
808851
809-
I encourage developers to integrate `nextjs-centralized-error-handler` into their projects and share their experiences. Whether it’s bug reports, suggestions for improvement, or simply sharing how it has helped streamline error management in your applications, your feedback is invaluable. Together, we can enhance this package and make it even more effective for the Next.js community.
852+
I encourage developers to try out the nextjs-centralized-error-handler package and share their experiences. Whether it’s bug reports, improvement suggestions, or simply sharing how it has helped streamline error management in your applications, your feedback is invaluable. Together, we can enhance this package and make it even more effective for the Next.js community.
810853
811854
---
812855

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.16-beta.1",
3+
"version": "1.0.17",
44
"main": "src/index.js",
55
"scripts": {
66
"test": "jest",

0 commit comments

Comments
 (0)