Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ constructor(status, message, properties)
Where:

- `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.
- `message`: The error message. This is optional.
- `message`: The error message. This is optional. If not provided, the default HTTP status code description will be used.
- `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.

The returned instance is a descendant class of `Error` with the following base properties, plus all the other properties specified in the constructor:
Expand Down
9 changes: 7 additions & 2 deletions src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ export class HttpError extends Error {

constructor(status: number | string, message?: string | GenericObject, properties?: GenericObject) {
// Normalize arguments
if (typeof message === 'object') {
if (typeof message === 'object' && message !== null) {
properties = message
message = properties.message || ''
message = properties.message
}

if (!properties) {
Expand All @@ -37,6 +37,11 @@ export class HttpError extends Error {
status = 500
}

// Add default message if none provided
if (typeof message !== 'string') {
message = messagesByCodes[status] || ''
}

// Extract special properties for Error constructor
const errorOptions: ErrorOptions = {}
if (properties.cause) {
Expand Down
8 changes: 8 additions & 0 deletions test/base.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ test('HttpError', async () => {
deepStrictEqual(otherError.code, 'HTTP_ERROR_570')
})

await test('it should use a default message', () => {
const error = new HttpError(404)
const otherError = new HttpError(404, { key1: 'value1' })

deepStrictEqual(error.message, 'Not Found')
deepStrictEqual(otherError.message, 'Not Found')
})

await test('it should support cause', () => {
const cause = new Error('WHATEVER')
const error = new HttpError(404, 'WHATEVER', { key1: 'value1', cause })
Expand Down