@wnodex/errors 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +7 -0
- package/LICENSE +21 -0
- package/README.md +19 -0
- package/dist/base-error.d.ts +57 -0
- package/dist/base-error.d.ts.map +1 -0
- package/dist/base-error.js +90 -0
- package/dist/config-error.d.ts +20 -0
- package/dist/config-error.d.ts.map +1 -0
- package/dist/config-error.js +26 -0
- package/dist/error-codes.d.ts +10 -0
- package/dist/error-codes.d.ts.map +1 -0
- package/dist/error-codes.js +9 -0
- package/dist/error-handler.d.ts +4 -0
- package/dist/error-handler.d.ts.map +1 -0
- package/dist/error-handler.js +22 -0
- package/dist/error-metadata.d.ts +18 -0
- package/dist/error-metadata.d.ts.map +1 -0
- package/dist/error-metadata.js +9 -0
- package/dist/http-error.d.ts +17 -0
- package/dist/http-error.d.ts.map +1 -0
- package/dist/http-error.js +20 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/validation-error.d.ts +19 -0
- package/dist/validation-error.d.ts.map +1 -0
- package/dist/validation-error.js +25 -0
- package/package.json +49 -0
- package/rolldown.config.ts +20 -0
- package/src/base-error.ts +112 -0
- package/src/config-error.ts +31 -0
- package/src/error-codes.ts +9 -0
- package/src/error-handler.ts +36 -0
- package/src/error-metadata.ts +15 -0
- package/src/http-error.ts +21 -0
- package/src/index.ts +7 -0
- package/src/validation-error.ts +30 -0
- package/tsconfig.json +10 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Davide Di Criscito
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# @wnodex/errors
|
|
2
|
+
|
|
3
|
+
wnodex custom application errors
|
|
4
|
+
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
## Table of Content
|
|
8
|
+
|
|
9
|
+
- [License](#license)
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## License
|
|
14
|
+
|
|
15
|
+
This project is licensed under the MIT License.
|
|
16
|
+
|
|
17
|
+
**Copyright (c) 2026 Davide Di Criscito**
|
|
18
|
+
|
|
19
|
+
For the full details, see the [LICENSE](LICENSE) file.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { ErrorMetadataInput } from './error-metadata.js';
|
|
2
|
+
/**
|
|
3
|
+
* Base class for all custom application errors.
|
|
4
|
+
* Extends the native `Error` to preserve stack traces and adds structured, validated metadata.
|
|
5
|
+
*
|
|
6
|
+
* Provides consistent error information for debugging and structured logging.
|
|
7
|
+
*/
|
|
8
|
+
export declare class BaseError extends Error {
|
|
9
|
+
/**
|
|
10
|
+
* The machine-readable error code, suitable for programmatic handling.
|
|
11
|
+
* @readonly
|
|
12
|
+
*/
|
|
13
|
+
readonly code: string;
|
|
14
|
+
/**
|
|
15
|
+
* The optional cause that triggered this error instance.
|
|
16
|
+
* May be any value, but usually another Error object for chained errors.
|
|
17
|
+
* @override
|
|
18
|
+
* @readonly
|
|
19
|
+
*/
|
|
20
|
+
readonly cause?: unknown;
|
|
21
|
+
/**
|
|
22
|
+
* Additional error context for debugging (may contain any serializable data).
|
|
23
|
+
* @readonly
|
|
24
|
+
*/
|
|
25
|
+
readonly context?: unknown;
|
|
26
|
+
/**
|
|
27
|
+
* Constructs a new instance of BaseError.
|
|
28
|
+
* Validates the provided metadata to ensure it matches the ErrorMetadataSchema.
|
|
29
|
+
* @param message The human-readable error message.
|
|
30
|
+
* @param metadata Structured metadata for this error instance. It will be validated.
|
|
31
|
+
* @throws {Error} Throws if the metadata is invalid according to ErrorMetadataSchema.
|
|
32
|
+
* @example
|
|
33
|
+
* const err = new BaseError('User not found', { code: 'USER_NOT_FOUND' });
|
|
34
|
+
*/
|
|
35
|
+
constructor(message: string, metadata: ErrorMetadataInput);
|
|
36
|
+
/**
|
|
37
|
+
* Validates the error metadata using ErrorMetadataSchema.
|
|
38
|
+
* Throws a clear error if validation fails, including the original Zod error as the cause.
|
|
39
|
+
* @param input The raw metadata input.
|
|
40
|
+
* @param parentErrorMessage The message of the error being constructed, for improved diagnostics.
|
|
41
|
+
* @returns {ErrorMetadataOutput} Parsed and validated metadata.
|
|
42
|
+
* @throws {Error} If the metadata does not pass validation.
|
|
43
|
+
* @example
|
|
44
|
+
* this.validateMetadata({ code: 'INVALID', context: { foo: 42 } }, 'Something failed');
|
|
45
|
+
*/
|
|
46
|
+
private validateMetadata;
|
|
47
|
+
/**
|
|
48
|
+
* Returns a plain object representation of the error,
|
|
49
|
+
* useful for structured logging, serialization, or external error reporting.
|
|
50
|
+
* Nested error causes include their name, message, and stack trace.
|
|
51
|
+
* @returns {object} A plain, serializable object representing this error.
|
|
52
|
+
* @example
|
|
53
|
+
* JSON.stringify(err.toJSON());
|
|
54
|
+
*/
|
|
55
|
+
toJSON(): object;
|
|
56
|
+
}
|
|
57
|
+
//# sourceMappingURL=base-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base-error.d.ts","sourceRoot":"","sources":["../src/base-error.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,kBAAkB,EAEnB,MAAM,qBAAqB,CAAC;AAG7B;;;;;GAKG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC;;;OAGG;IACH,SAAgB,IAAI,EAAE,MAAM,CAAC;IAE7B;;;;;OAKG;IACH,SAAgB,KAAK,CAAC,EAAE,OAAO,CAAC;IAEhC;;;OAGG;IACH,SAAgB,OAAO,CAAC,EAAE,OAAO,CAAC;IAElC;;;;;;;;OAQG;gBACS,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,kBAAkB;IAgBzD;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;IAgBxB;;;;;;;OAOG;IACH,MAAM,IAAI,MAAM;CAmBjB"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { ErrorMetadataSchema } from './error-metadata.js';
|
|
2
|
+
/**
|
|
3
|
+
* Base class for all custom application errors.
|
|
4
|
+
* Extends the native `Error` to preserve stack traces and adds structured, validated metadata.
|
|
5
|
+
*
|
|
6
|
+
* Provides consistent error information for debugging and structured logging.
|
|
7
|
+
*/
|
|
8
|
+
export class BaseError extends Error {
|
|
9
|
+
/**
|
|
10
|
+
* The machine-readable error code, suitable for programmatic handling.
|
|
11
|
+
* @readonly
|
|
12
|
+
*/
|
|
13
|
+
code;
|
|
14
|
+
/**
|
|
15
|
+
* The optional cause that triggered this error instance.
|
|
16
|
+
* May be any value, but usually another Error object for chained errors.
|
|
17
|
+
* @override
|
|
18
|
+
* @readonly
|
|
19
|
+
*/
|
|
20
|
+
cause;
|
|
21
|
+
/**
|
|
22
|
+
* Additional error context for debugging (may contain any serializable data).
|
|
23
|
+
* @readonly
|
|
24
|
+
*/
|
|
25
|
+
context;
|
|
26
|
+
/**
|
|
27
|
+
* Constructs a new instance of BaseError.
|
|
28
|
+
* Validates the provided metadata to ensure it matches the ErrorMetadataSchema.
|
|
29
|
+
* @param message The human-readable error message.
|
|
30
|
+
* @param metadata Structured metadata for this error instance. It will be validated.
|
|
31
|
+
* @throws {Error} Throws if the metadata is invalid according to ErrorMetadataSchema.
|
|
32
|
+
* @example
|
|
33
|
+
* const err = new BaseError('User not found', { code: 'USER_NOT_FOUND' });
|
|
34
|
+
*/
|
|
35
|
+
constructor(message, metadata) {
|
|
36
|
+
super(message);
|
|
37
|
+
// Sets the name property to the actual class name (useful with inheritance).
|
|
38
|
+
this.name = new.target.name;
|
|
39
|
+
const validatedMetadata = this.validateMetadata(metadata, message);
|
|
40
|
+
this.code = validatedMetadata.code;
|
|
41
|
+
this.cause = validatedMetadata.cause;
|
|
42
|
+
this.context = validatedMetadata.context;
|
|
43
|
+
// Ensures proper prototype chain for custom errors (required for ES5/TypeScript).
|
|
44
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Validates the error metadata using ErrorMetadataSchema.
|
|
48
|
+
* Throws a clear error if validation fails, including the original Zod error as the cause.
|
|
49
|
+
* @param input The raw metadata input.
|
|
50
|
+
* @param parentErrorMessage The message of the error being constructed, for improved diagnostics.
|
|
51
|
+
* @returns {ErrorMetadataOutput} Parsed and validated metadata.
|
|
52
|
+
* @throws {Error} If the metadata does not pass validation.
|
|
53
|
+
* @example
|
|
54
|
+
* this.validateMetadata({ code: 'INVALID', context: { foo: 42 } }, 'Something failed');
|
|
55
|
+
*/
|
|
56
|
+
validateMetadata(input, parentErrorMessage) {
|
|
57
|
+
const result = ErrorMetadataSchema.safeParse(input);
|
|
58
|
+
if (!result.success) {
|
|
59
|
+
const errorMessage = `Invalid metadata provided for error "${parentErrorMessage}" (Code: ${input.code || 'N/A'}).`;
|
|
60
|
+
console.error(result.error);
|
|
61
|
+
throw new Error(errorMessage);
|
|
62
|
+
}
|
|
63
|
+
return result.data;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Returns a plain object representation of the error,
|
|
67
|
+
* useful for structured logging, serialization, or external error reporting.
|
|
68
|
+
* Nested error causes include their name, message, and stack trace.
|
|
69
|
+
* @returns {object} A plain, serializable object representing this error.
|
|
70
|
+
* @example
|
|
71
|
+
* JSON.stringify(err.toJSON());
|
|
72
|
+
*/
|
|
73
|
+
toJSON() {
|
|
74
|
+
const normalizedCause = this.cause instanceof Error
|
|
75
|
+
? {
|
|
76
|
+
name: this.cause.name,
|
|
77
|
+
message: this.cause.message,
|
|
78
|
+
stack: this.cause.stack,
|
|
79
|
+
}
|
|
80
|
+
: this.cause;
|
|
81
|
+
return {
|
|
82
|
+
name: this.name,
|
|
83
|
+
message: this.message,
|
|
84
|
+
code: this.code,
|
|
85
|
+
cause: normalizedCause,
|
|
86
|
+
context: this.context,
|
|
87
|
+
stack: this.stack,
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { BaseError } from './base-error.js';
|
|
2
|
+
/**
|
|
3
|
+
* Custom error class for configuration failures.
|
|
4
|
+
* Represents issues occurring during loading, parsing, or applying application configuration.
|
|
5
|
+
* Automatically sets the error code to `"CONFIG_ERROR"`. Useful for problems involving environment
|
|
6
|
+
* variables, config files, or settings.
|
|
7
|
+
*/
|
|
8
|
+
export declare class ConfigError extends BaseError {
|
|
9
|
+
/**
|
|
10
|
+
* Constructs a new ConfigError instance.
|
|
11
|
+
* @param message The human-readable error message describing the configuration problem.
|
|
12
|
+
* @param cause Optional original error or value that triggered the configuration failure, such as a file system or validation error.
|
|
13
|
+
* @param context Optional additional context data, such as the config file path, setting name, or problematic value.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* throw new ConfigError('Failed to load config file', readError, { file: './config.json' });
|
|
17
|
+
*/
|
|
18
|
+
constructor(message: string, cause?: unknown, context?: Record<string | number | symbol, unknown>);
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=config-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config-error.d.ts","sourceRoot":"","sources":["../src/config-error.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C;;;;;GAKG;AACH,qBAAa,WAAY,SAAQ,SAAS;IACxC;;;;;;;;OAQG;gBAED,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,OAAO,EACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC;CAQtD"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { ERROR_CODES } from './error-codes.js';
|
|
2
|
+
import { BaseError } from './base-error.js';
|
|
3
|
+
/**
|
|
4
|
+
* Custom error class for configuration failures.
|
|
5
|
+
* Represents issues occurring during loading, parsing, or applying application configuration.
|
|
6
|
+
* Automatically sets the error code to `"CONFIG_ERROR"`. Useful for problems involving environment
|
|
7
|
+
* variables, config files, or settings.
|
|
8
|
+
*/
|
|
9
|
+
export class ConfigError extends BaseError {
|
|
10
|
+
/**
|
|
11
|
+
* Constructs a new ConfigError instance.
|
|
12
|
+
* @param message The human-readable error message describing the configuration problem.
|
|
13
|
+
* @param cause Optional original error or value that triggered the configuration failure, such as a file system or validation error.
|
|
14
|
+
* @param context Optional additional context data, such as the config file path, setting name, or problematic value.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* throw new ConfigError('Failed to load config file', readError, { file: './config.json' });
|
|
18
|
+
*/
|
|
19
|
+
constructor(message, cause, context) {
|
|
20
|
+
super(message, {
|
|
21
|
+
code: ERROR_CODES.CONFIG_ERROR,
|
|
22
|
+
cause,
|
|
23
|
+
context,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare const ERROR_CODES: {
|
|
2
|
+
readonly VALIDATION_ERROR: "VALIDATION_ERROR";
|
|
3
|
+
readonly CONFIG_ERROR: "CONFIG_ERROR";
|
|
4
|
+
readonly INTERNAL_ERROR: "INTERNAL_ERROR";
|
|
5
|
+
readonly NOT_FOUND: "NOT_FOUND";
|
|
6
|
+
readonly UNAUTHORIZED: "UNAUTHORIZED";
|
|
7
|
+
readonly FORBIDDEN: "FORBIDDEN";
|
|
8
|
+
readonly BAD_REQUEST: "BAD_REQUEST";
|
|
9
|
+
};
|
|
10
|
+
//# sourceMappingURL=error-codes.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-codes.d.ts","sourceRoot":"","sources":["../src/error-codes.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW;;;;;;;;CAQd,CAAC"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
2
|
+
import { HttpError } from './http-error.js';
|
|
3
|
+
export declare const errorHandler: (err: HttpError | Error, _req: Request, res: Response, _next: NextFunction) => void;
|
|
4
|
+
//# sourceMappingURL=error-handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-handler.d.ts","sourceRoot":"","sources":["../src/error-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAE/D,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C,eAAO,MAAM,YAAY,GACvB,KAAK,SAAS,GAAG,KAAK,EACtB,MAAM,OAAO,EACb,KAAK,QAAQ,EACb,OAAO,YAAY,SA2BpB,CAAC"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const errorHandler = (err, _req, res, _next) => {
|
|
2
|
+
// Log the error for server debugging
|
|
3
|
+
console.error(err);
|
|
4
|
+
// Determine HTTP status code; default to 500 if unavailable
|
|
5
|
+
const statusCode = typeof err === 'object' && err !== null && 'statusCode' in err
|
|
6
|
+
? err.statusCode
|
|
7
|
+
: 500;
|
|
8
|
+
// Get message or default to 'Internal Server Error'
|
|
9
|
+
const message = typeof err === 'object' && err !== null && 'message' in err
|
|
10
|
+
? err.message
|
|
11
|
+
: 'Internal Server Error';
|
|
12
|
+
// Send JSON response
|
|
13
|
+
res.status(statusCode).json({
|
|
14
|
+
error: {
|
|
15
|
+
message,
|
|
16
|
+
// Show stack trace only in development environment
|
|
17
|
+
...(process.env.NODE_ENV !== 'production' && {
|
|
18
|
+
stack: err.stack,
|
|
19
|
+
}),
|
|
20
|
+
},
|
|
21
|
+
});
|
|
22
|
+
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export declare const ErrorMetadataSchema: z.ZodObject<{
|
|
3
|
+
code: z.ZodEnum<{
|
|
4
|
+
VALIDATION_ERROR: "VALIDATION_ERROR";
|
|
5
|
+
CONFIG_ERROR: "CONFIG_ERROR";
|
|
6
|
+
INTERNAL_ERROR: "INTERNAL_ERROR";
|
|
7
|
+
NOT_FOUND: "NOT_FOUND";
|
|
8
|
+
UNAUTHORIZED: "UNAUTHORIZED";
|
|
9
|
+
FORBIDDEN: "FORBIDDEN";
|
|
10
|
+
BAD_REQUEST: "BAD_REQUEST";
|
|
11
|
+
}>;
|
|
12
|
+
cause: z.ZodOptional<z.ZodUnknown>;
|
|
13
|
+
context: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
|
|
14
|
+
}, z.core.$strict>;
|
|
15
|
+
export type ErrorMetadata = z.infer<typeof ErrorMetadataSchema>;
|
|
16
|
+
export type ErrorMetadataInput = z.input<typeof ErrorMetadataSchema>;
|
|
17
|
+
export type ErrorMetadataOutput = z.output<typeof ErrorMetadataSchema>;
|
|
18
|
+
//# sourceMappingURL=error-metadata.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-metadata.d.ts","sourceRoot":"","sources":["../src/error-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,eAAO,MAAM,mBAAmB;;;;;;;;;;;;kBAMrB,CAAC;AAEZ,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAChE,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AACrE,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,mBAAmB,CAAC,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { ERROR_CODES } from './error-codes.js';
|
|
3
|
+
export const ErrorMetadataSchema = z
|
|
4
|
+
.object({
|
|
5
|
+
code: z.enum(Object.values(ERROR_CODES)),
|
|
6
|
+
cause: z.unknown().optional(),
|
|
7
|
+
context: z.record(z.string(), z.unknown()).optional(),
|
|
8
|
+
})
|
|
9
|
+
.strict();
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom HTTP error class with status code.
|
|
3
|
+
* Represents an HTTP error with both status code and message.
|
|
4
|
+
*/
|
|
5
|
+
export declare class HttpError extends Error {
|
|
6
|
+
readonly statusCode: number;
|
|
7
|
+
/**
|
|
8
|
+
* Creates an instance of HttpError.
|
|
9
|
+
* @param message Error message describing the problem.
|
|
10
|
+
* @param statusCode HTTP status code, default is 500.
|
|
11
|
+
* @example
|
|
12
|
+
* // Throws an error with 404 status code
|
|
13
|
+
* throw new HttpError('Not Found', 404);
|
|
14
|
+
*/
|
|
15
|
+
constructor(message: string, statusCode?: number);
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=http-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http-error.d.ts","sourceRoot":"","sources":["../src/http-error.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,qBAAa,SAAU,SAAQ,KAAK;IAClC,SAAgB,UAAU,EAAE,MAAM,CAAC;IAEnC;;;;;;;OAOG;gBACS,OAAO,EAAE,MAAM,EAAE,UAAU,SAAM;CAK9C"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom HTTP error class with status code.
|
|
3
|
+
* Represents an HTTP error with both status code and message.
|
|
4
|
+
*/
|
|
5
|
+
export class HttpError extends Error {
|
|
6
|
+
statusCode;
|
|
7
|
+
/**
|
|
8
|
+
* Creates an instance of HttpError.
|
|
9
|
+
* @param message Error message describing the problem.
|
|
10
|
+
* @param statusCode HTTP status code, default is 500.
|
|
11
|
+
* @example
|
|
12
|
+
* // Throws an error with 404 status code
|
|
13
|
+
* throw new HttpError('Not Found', 404);
|
|
14
|
+
*/
|
|
15
|
+
constructor(message, statusCode = 500) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.statusCode = statusCode;
|
|
18
|
+
this.name = this.constructor.name;
|
|
19
|
+
}
|
|
20
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './base-error.js';
|
|
2
|
+
export * from './config-error.js';
|
|
3
|
+
export * from './error-codes.js';
|
|
4
|
+
export * from './error-handler.js';
|
|
5
|
+
export * from './error-metadata.js';
|
|
6
|
+
export * from './http-error.js';
|
|
7
|
+
export * from './validation-error.js';
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,qBAAqB,CAAC;AACpC,cAAc,iBAAiB,CAAC;AAChC,cAAc,uBAAuB,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { BaseError } from './base-error.js';
|
|
2
|
+
/**
|
|
3
|
+
* Custom error class for validation failures.
|
|
4
|
+
* Used for input errors, schema violations, or data integrity issues.
|
|
5
|
+
* Automatically sets the error code to `"VALIDATION_ERROR"` to allow standard handling of validation errors.
|
|
6
|
+
*/
|
|
7
|
+
export declare class ValidationError extends BaseError {
|
|
8
|
+
/**
|
|
9
|
+
* Constructs a new ValidationError instance.
|
|
10
|
+
* @param message The human-readable error message describing what failed validation.
|
|
11
|
+
* @param cause Optional original error or value that caused the validation failure, such as a ZodError or validation detail.
|
|
12
|
+
* @param context Optional additional context data, for example the invalid field, config path, or offending input.
|
|
13
|
+
*
|
|
14
|
+
* @example
|
|
15
|
+
* throw new ValidationError('Invalid email format', zodResult.error, { field: 'email' });
|
|
16
|
+
*/
|
|
17
|
+
constructor(message: string, cause?: unknown, context?: Record<string | number | symbol, unknown>);
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=validation-error.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"validation-error.d.ts","sourceRoot":"","sources":["../src/validation-error.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAE5C;;;;GAIG;AACH,qBAAa,eAAgB,SAAQ,SAAS;IAC5C;;;;;;;;OAQG;gBAED,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,OAAO,EACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,GAAG,MAAM,GAAG,MAAM,EAAE,OAAO,CAAC;CAQtD"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { ERROR_CODES } from './error-codes.js';
|
|
2
|
+
import { BaseError } from './base-error.js';
|
|
3
|
+
/**
|
|
4
|
+
* Custom error class for validation failures.
|
|
5
|
+
* Used for input errors, schema violations, or data integrity issues.
|
|
6
|
+
* Automatically sets the error code to `"VALIDATION_ERROR"` to allow standard handling of validation errors.
|
|
7
|
+
*/
|
|
8
|
+
export class ValidationError extends BaseError {
|
|
9
|
+
/**
|
|
10
|
+
* Constructs a new ValidationError instance.
|
|
11
|
+
* @param message The human-readable error message describing what failed validation.
|
|
12
|
+
* @param cause Optional original error or value that caused the validation failure, such as a ZodError or validation detail.
|
|
13
|
+
* @param context Optional additional context data, for example the invalid field, config path, or offending input.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* throw new ValidationError('Invalid email format', zodResult.error, { field: 'email' });
|
|
17
|
+
*/
|
|
18
|
+
constructor(message, cause, context) {
|
|
19
|
+
super(message, {
|
|
20
|
+
code: ERROR_CODES.VALIDATION_ERROR,
|
|
21
|
+
cause,
|
|
22
|
+
context,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@wnodex/errors",
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"private": false,
|
|
5
|
+
"description": "wnodex custom application errors",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"wnodex",
|
|
8
|
+
"errors"
|
|
9
|
+
],
|
|
10
|
+
"homepage": "https://github.com/wnodex/wnodex#readme",
|
|
11
|
+
"bugs": {
|
|
12
|
+
"url": "https://github.com/wnodex/wnodex/issues"
|
|
13
|
+
},
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/wnodex/wnodex.git",
|
|
17
|
+
"directory": "packages/errors"
|
|
18
|
+
},
|
|
19
|
+
"license": "MIT",
|
|
20
|
+
"type": "module",
|
|
21
|
+
"exports": {
|
|
22
|
+
"./package.json": "./package.json",
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"import": "./dist/index.js",
|
|
26
|
+
"default": "./dist/index.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"main": "./dist/index.js",
|
|
30
|
+
"module": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"express": "^5.2.1",
|
|
34
|
+
"zod": "^4.3.6"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/express": "^5.0.6",
|
|
38
|
+
"@types/node": "^25.0.10",
|
|
39
|
+
"rolldown": "1.0.0-rc.1",
|
|
40
|
+
"typescript": "5.9.2",
|
|
41
|
+
"@wnodex/typescript-config": "0.2.1"
|
|
42
|
+
},
|
|
43
|
+
"publishConfig": {
|
|
44
|
+
"access": "public"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "rolldown -c && tsc"
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { defineConfig } from 'rolldown';
|
|
2
|
+
|
|
3
|
+
export default defineConfig([
|
|
4
|
+
{
|
|
5
|
+
input: ['src/index.ts'],
|
|
6
|
+
output: {
|
|
7
|
+
format: 'esm',
|
|
8
|
+
dir: 'dist',
|
|
9
|
+
entryFileNames: '[name].js',
|
|
10
|
+
chunkFileNames: '[name]-[hash].js',
|
|
11
|
+
assetFileNames: '[name]-[hash][extname]',
|
|
12
|
+
},
|
|
13
|
+
platform: 'node',
|
|
14
|
+
external: (id) => {
|
|
15
|
+
if (id.startsWith('node:')) return true;
|
|
16
|
+
if (id.startsWith('.') || id.startsWith('/')) return false;
|
|
17
|
+
return true;
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
]);
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ErrorMetadataInput,
|
|
3
|
+
ErrorMetadataOutput,
|
|
4
|
+
} from './error-metadata.js';
|
|
5
|
+
import { ErrorMetadataSchema } from './error-metadata.js';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Base class for all custom application errors.
|
|
9
|
+
* Extends the native `Error` to preserve stack traces and adds structured, validated metadata.
|
|
10
|
+
*
|
|
11
|
+
* Provides consistent error information for debugging and structured logging.
|
|
12
|
+
*/
|
|
13
|
+
export class BaseError extends Error {
|
|
14
|
+
/**
|
|
15
|
+
* The machine-readable error code, suitable for programmatic handling.
|
|
16
|
+
* @readonly
|
|
17
|
+
*/
|
|
18
|
+
public readonly code: string;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The optional cause that triggered this error instance.
|
|
22
|
+
* May be any value, but usually another Error object for chained errors.
|
|
23
|
+
* @override
|
|
24
|
+
* @readonly
|
|
25
|
+
*/
|
|
26
|
+
public readonly cause?: unknown;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Additional error context for debugging (may contain any serializable data).
|
|
30
|
+
* @readonly
|
|
31
|
+
*/
|
|
32
|
+
public readonly context?: unknown;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Constructs a new instance of BaseError.
|
|
36
|
+
* Validates the provided metadata to ensure it matches the ErrorMetadataSchema.
|
|
37
|
+
* @param message The human-readable error message.
|
|
38
|
+
* @param metadata Structured metadata for this error instance. It will be validated.
|
|
39
|
+
* @throws {Error} Throws if the metadata is invalid according to ErrorMetadataSchema.
|
|
40
|
+
* @example
|
|
41
|
+
* const err = new BaseError('User not found', { code: 'USER_NOT_FOUND' });
|
|
42
|
+
*/
|
|
43
|
+
constructor(message: string, metadata: ErrorMetadataInput) {
|
|
44
|
+
super(message);
|
|
45
|
+
|
|
46
|
+
// Sets the name property to the actual class name (useful with inheritance).
|
|
47
|
+
this.name = new.target.name;
|
|
48
|
+
|
|
49
|
+
const validatedMetadata = this.validateMetadata(metadata, message);
|
|
50
|
+
|
|
51
|
+
this.code = validatedMetadata.code;
|
|
52
|
+
this.cause = validatedMetadata.cause;
|
|
53
|
+
this.context = validatedMetadata.context;
|
|
54
|
+
|
|
55
|
+
// Ensures proper prototype chain for custom errors (required for ES5/TypeScript).
|
|
56
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Validates the error metadata using ErrorMetadataSchema.
|
|
61
|
+
* Throws a clear error if validation fails, including the original Zod error as the cause.
|
|
62
|
+
* @param input The raw metadata input.
|
|
63
|
+
* @param parentErrorMessage The message of the error being constructed, for improved diagnostics.
|
|
64
|
+
* @returns {ErrorMetadataOutput} Parsed and validated metadata.
|
|
65
|
+
* @throws {Error} If the metadata does not pass validation.
|
|
66
|
+
* @example
|
|
67
|
+
* this.validateMetadata({ code: 'INVALID', context: { foo: 42 } }, 'Something failed');
|
|
68
|
+
*/
|
|
69
|
+
private validateMetadata(
|
|
70
|
+
input: ErrorMetadataInput,
|
|
71
|
+
parentErrorMessage: string
|
|
72
|
+
): ErrorMetadataOutput {
|
|
73
|
+
const result = ErrorMetadataSchema.safeParse(input);
|
|
74
|
+
|
|
75
|
+
if (!result.success) {
|
|
76
|
+
const errorMessage = `Invalid metadata provided for error "${parentErrorMessage}" (Code: ${input.code || 'N/A'}).`;
|
|
77
|
+
|
|
78
|
+
console.error(result.error);
|
|
79
|
+
throw new Error(errorMessage);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return result.data;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Returns a plain object representation of the error,
|
|
87
|
+
* useful for structured logging, serialization, or external error reporting.
|
|
88
|
+
* Nested error causes include their name, message, and stack trace.
|
|
89
|
+
* @returns {object} A plain, serializable object representing this error.
|
|
90
|
+
* @example
|
|
91
|
+
* JSON.stringify(err.toJSON());
|
|
92
|
+
*/
|
|
93
|
+
toJSON(): object {
|
|
94
|
+
const normalizedCause =
|
|
95
|
+
this.cause instanceof Error
|
|
96
|
+
? {
|
|
97
|
+
name: this.cause.name,
|
|
98
|
+
message: this.cause.message,
|
|
99
|
+
stack: this.cause.stack,
|
|
100
|
+
}
|
|
101
|
+
: this.cause;
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
name: this.name,
|
|
105
|
+
message: this.message,
|
|
106
|
+
code: this.code,
|
|
107
|
+
cause: normalizedCause,
|
|
108
|
+
context: this.context,
|
|
109
|
+
stack: this.stack,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ERROR_CODES } from './error-codes.js';
|
|
2
|
+
import { BaseError } from './base-error.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Custom error class for configuration failures.
|
|
6
|
+
* Represents issues occurring during loading, parsing, or applying application configuration.
|
|
7
|
+
* Automatically sets the error code to `"CONFIG_ERROR"`. Useful for problems involving environment
|
|
8
|
+
* variables, config files, or settings.
|
|
9
|
+
*/
|
|
10
|
+
export class ConfigError extends BaseError {
|
|
11
|
+
/**
|
|
12
|
+
* Constructs a new ConfigError instance.
|
|
13
|
+
* @param message The human-readable error message describing the configuration problem.
|
|
14
|
+
* @param cause Optional original error or value that triggered the configuration failure, such as a file system or validation error.
|
|
15
|
+
* @param context Optional additional context data, such as the config file path, setting name, or problematic value.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* throw new ConfigError('Failed to load config file', readError, { file: './config.json' });
|
|
19
|
+
*/
|
|
20
|
+
constructor(
|
|
21
|
+
message: string,
|
|
22
|
+
cause?: unknown,
|
|
23
|
+
context?: Record<string | number | symbol, unknown>
|
|
24
|
+
) {
|
|
25
|
+
super(message, {
|
|
26
|
+
code: ERROR_CODES.CONFIG_ERROR,
|
|
27
|
+
cause,
|
|
28
|
+
context,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const ERROR_CODES = {
|
|
2
|
+
VALIDATION_ERROR: 'VALIDATION_ERROR',
|
|
3
|
+
CONFIG_ERROR: 'CONFIG_ERROR',
|
|
4
|
+
INTERNAL_ERROR: 'INTERNAL_ERROR',
|
|
5
|
+
NOT_FOUND: 'NOT_FOUND',
|
|
6
|
+
UNAUTHORIZED: 'UNAUTHORIZED',
|
|
7
|
+
FORBIDDEN: 'FORBIDDEN',
|
|
8
|
+
BAD_REQUEST: 'BAD_REQUEST',
|
|
9
|
+
} as const;
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { NextFunction, Request, Response } from 'express';
|
|
2
|
+
|
|
3
|
+
import { HttpError } from './http-error.js';
|
|
4
|
+
|
|
5
|
+
export const errorHandler = (
|
|
6
|
+
err: HttpError | Error,
|
|
7
|
+
_req: Request,
|
|
8
|
+
res: Response,
|
|
9
|
+
_next: NextFunction
|
|
10
|
+
) => {
|
|
11
|
+
// Log the error for server debugging
|
|
12
|
+
console.error(err);
|
|
13
|
+
|
|
14
|
+
// Determine HTTP status code; default to 500 if unavailable
|
|
15
|
+
const statusCode =
|
|
16
|
+
typeof err === 'object' && err !== null && 'statusCode' in err
|
|
17
|
+
? err.statusCode
|
|
18
|
+
: 500;
|
|
19
|
+
|
|
20
|
+
// Get message or default to 'Internal Server Error'
|
|
21
|
+
const message =
|
|
22
|
+
typeof err === 'object' && err !== null && 'message' in err
|
|
23
|
+
? err.message
|
|
24
|
+
: 'Internal Server Error';
|
|
25
|
+
|
|
26
|
+
// Send JSON response
|
|
27
|
+
res.status(statusCode).json({
|
|
28
|
+
error: {
|
|
29
|
+
message,
|
|
30
|
+
// Show stack trace only in development environment
|
|
31
|
+
...(process.env.NODE_ENV !== 'production' && {
|
|
32
|
+
stack: err.stack,
|
|
33
|
+
}),
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
import { ERROR_CODES } from './error-codes.js';
|
|
4
|
+
|
|
5
|
+
export const ErrorMetadataSchema = z
|
|
6
|
+
.object({
|
|
7
|
+
code: z.enum(Object.values(ERROR_CODES)),
|
|
8
|
+
cause: z.unknown().optional(),
|
|
9
|
+
context: z.record(z.string(), z.unknown()).optional(),
|
|
10
|
+
})
|
|
11
|
+
.strict();
|
|
12
|
+
|
|
13
|
+
export type ErrorMetadata = z.infer<typeof ErrorMetadataSchema>;
|
|
14
|
+
export type ErrorMetadataInput = z.input<typeof ErrorMetadataSchema>;
|
|
15
|
+
export type ErrorMetadataOutput = z.output<typeof ErrorMetadataSchema>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom HTTP error class with status code.
|
|
3
|
+
* Represents an HTTP error with both status code and message.
|
|
4
|
+
*/
|
|
5
|
+
export class HttpError extends Error {
|
|
6
|
+
public readonly statusCode: number;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Creates an instance of HttpError.
|
|
10
|
+
* @param message Error message describing the problem.
|
|
11
|
+
* @param statusCode HTTP status code, default is 500.
|
|
12
|
+
* @example
|
|
13
|
+
* // Throws an error with 404 status code
|
|
14
|
+
* throw new HttpError('Not Found', 404);
|
|
15
|
+
*/
|
|
16
|
+
constructor(message: string, statusCode = 500) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.statusCode = statusCode;
|
|
19
|
+
this.name = this.constructor.name;
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { ERROR_CODES } from './error-codes.js';
|
|
2
|
+
import { BaseError } from './base-error.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Custom error class for validation failures.
|
|
6
|
+
* Used for input errors, schema violations, or data integrity issues.
|
|
7
|
+
* Automatically sets the error code to `"VALIDATION_ERROR"` to allow standard handling of validation errors.
|
|
8
|
+
*/
|
|
9
|
+
export class ValidationError extends BaseError {
|
|
10
|
+
/**
|
|
11
|
+
* Constructs a new ValidationError instance.
|
|
12
|
+
* @param message The human-readable error message describing what failed validation.
|
|
13
|
+
* @param cause Optional original error or value that caused the validation failure, such as a ZodError or validation detail.
|
|
14
|
+
* @param context Optional additional context data, for example the invalid field, config path, or offending input.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* throw new ValidationError('Invalid email format', zodResult.error, { field: 'email' });
|
|
18
|
+
*/
|
|
19
|
+
constructor(
|
|
20
|
+
message: string,
|
|
21
|
+
cause?: unknown,
|
|
22
|
+
context?: Record<string | number | symbol, unknown>
|
|
23
|
+
) {
|
|
24
|
+
super(message, {
|
|
25
|
+
code: ERROR_CODES.VALIDATION_ERROR,
|
|
26
|
+
cause,
|
|
27
|
+
context,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
}
|
package/tsconfig.json
ADDED