diff --git a/README.md b/README.md index a708300..8379789 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/src/base.ts b/src/base.ts index ccf17cc..bf66f3e 100644 --- a/src/base.ts +++ b/src/base.ts @@ -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) { @@ -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) { diff --git a/test/base.test.ts b/test/base.test.ts index ef67a40..b891833 100644 --- a/test/base.test.ts +++ b/test/base.test.ts @@ -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 })