Skip to content

Commit 980888c

Browse files
committed
feat: Add default message if none provided
1 parent d9347a6 commit 980888c

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ constructor(status, message, properties)
6868
Where:
6969

7070
- `status`: A HTTP status code as number or a identifier (like: `NotFound`). If the identifier is not valid or the number outside the validity range (`400 <= status <= 599`), it defaults to 500.
71-
- `message`: The error message. This is optional.
71+
- `message`: The error message. This is optional. If not provided, the default HTTP status code description will be used.
7272
- `properties`: A list of additional properties to attach to the error. With the exception of `code`, `message`, `stack`, `expose` and `headers`, all properties that already exist in the object are ignored. This is optional.
7373

7474
The returned instance is a descendant class of `Error` with the following base properties, plus all the other properties specified in the constructor:

src/base.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,9 @@ export class HttpError extends Error {
1818

1919
constructor(status: number | string, message?: string | GenericObject, properties?: GenericObject) {
2020
// Normalize arguments
21-
if (typeof message === 'object') {
21+
if (typeof message === 'object' && message !== null) {
2222
properties = message
23-
message = properties.message || ''
23+
message = properties.message
2424
}
2525

2626
if (!properties) {
@@ -37,6 +37,11 @@ export class HttpError extends Error {
3737
status = 500
3838
}
3939

40+
// Add default message if none provided
41+
if (typeof message !== 'string') {
42+
message = messagesByCodes[status] || ''
43+
}
44+
4045
// Extract special properties for Error constructor
4146
const errorOptions: ErrorOptions = {}
4247
if (properties.cause) {

test/base.test.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,14 @@ test('HttpError', async () => {
1919
deepStrictEqual(otherError.code, 'HTTP_ERROR_570')
2020
})
2121

22+
await test('it should use a default message', () => {
23+
const error = new HttpError(404)
24+
const otherError = new HttpError(404, { key1: 'value1' })
25+
26+
deepStrictEqual(error.message, 'Not Found')
27+
deepStrictEqual(otherError.message, 'Not Found')
28+
})
29+
2230
await test('it should support cause', () => {
2331
const cause = new Error('WHATEVER')
2432
const error = new HttpError(404, 'WHATEVER', { key1: 'value1', cause })

0 commit comments

Comments
 (0)