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
39 changes: 39 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,45 @@ console.log(new CustomError('world', {cause: new Error('cause')}))
// error.cause => Error('cause')
```

#### RFC 9457 problem details

The module also exports `createRFC9457Error`, which creates error objects that can be serialized as [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html) problem details objects (RFC 9457 obsoletes RFC 7807):

```js
createRFC9457Error(code, message [, statusCode [, opts [, Base [, captureStackTrace]]]])
```

It accepts the same parameters as `createError`, plus an optional `opts` object:

- `type` (`string`, optional) - A URI reference that identifies the problem type. Defaults to `'about:blank'`.
- `title` (`string`, optional) - A short, human-readable summary of the problem type. Defaults to the HTTP status reason phrase for the error's status code (e.g. `'Not Found'` for `404`).

The created error instances expose a `toProblemDetails(instance [, details])` method that returns the problem details object:

```js
const { createRFC9457Error } = require('@fastify/error')

const QuotaExceeded = createRFC9457Error(
'QUOTA_EXCEEDED',
'Quota exceeded by %d requests',
429,
{ type: 'https://example.net/probs/quota', title: 'Quota Exceeded' }
)

console.log(new QuotaExceeded(7).toProblemDetails('/api/limits', { retryAfter: 60 }))
// {
// type: 'https://example.net/probs/quota',
// title: 'Quota Exceeded',
// status: 429,
// detail: 'Quota exceeded by 7 requests',
// instance: '/api/limits',
// code: 'QUOTA_EXCEEDED',
// details: { retryAfter: 60 }
// }
```

`instance` is a URI reference that identifies the specific occurrence of the problem (e.g. the request path), and `details` carries additional extension members. `code` and `details` are [extension members](https://www.rfc-editor.org/rfc/rfc9457.html#name-extension-members) and are not defined by RFC 9457 itself.

### TypeScript

It is possible to limit your error constructor with a generic type using TypeScript:
Expand Down
34 changes: 34 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict'

const { STATUS_CODES } = require('node:http')
const { format } = require('node:util')

function toString () {
Expand Down Expand Up @@ -90,6 +91,38 @@ function createError (code, message, statusCode = 500, Base = Error, captureStac
return FastifyError
}

function createRFC9457Error (
code,
message,
statusCode = 500,
opts = {},
Base = Error,
captureStackTrace = createError.captureStackTrace
) {
const RFC9457Error = createError(code, message, statusCode, Base, captureStackTrace)

const type = opts.type || 'about:blank'
const title = opts.title

RFC9457Error.prototype.toProblemDetails = function (instance = '', details = {}) {
const status = this.statusCode ?? statusCode

return {
type,
// RFC 9457 recommends the HTTP status reason phrase as the title
// when no dedicated title is available
title: title || STATUS_CODES[status] || 'Unknown Error',
status,
detail: this.message,
instance,
code: this.code,
details
}
}

return RFC9457Error
}

createError.captureStackTrace = true

const FastifyErrorConstructor = createError(FastifyGenericErrorSymbol, 'Fastify Error', 500, Error)
Expand All @@ -98,3 +131,4 @@ module.exports = createError
module.exports.FastifyError = FastifyErrorConstructor
module.exports.default = createError
module.exports.createError = createError
module.exports.createRFC9457Error = createRFC9457Error
109 changes: 109 additions & 0 deletions test/rfc9457.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
'use strict'

const test = require('node:test')
const { createRFC9457Error } = require('..')

test('toProblemDetails() with defaults', (t) => {
t.plan(1)

const E = createRFC9457Error('CODE', 'oops')
const e = new E()
const pd = e.toProblemDetails()

t.assert.deepStrictEqual(pd, {
type: 'about:blank',
title: 'Internal Server Error',
status: 500,
detail: 'oops',
instance: '',
code: 'CODE',
details: {}
})
})

test('title defaults to the HTTP reason phrase for the status', (t) => {
t.plan(1)

const NotFound = createRFC9457Error('NOT_FOUND', 'user %s does not exist', 404)
const pd = new NotFound('alice').toProblemDetails('/users/alice')

t.assert.deepStrictEqual(pd, {
type: 'about:blank',
title: 'Not Found',
status: 404,
detail: 'user alice does not exist',
instance: '/users/alice',
code: 'NOT_FOUND',
details: {}
})
})

test('toProblemDetails() with custom type, title and extension details', (t) => {
t.plan(1)

const Warning = createRFC9457Error(
'WARN',
'Threshold exceeded by %d',
429,
{ type: 'https://example.net/probs/warn', title: 'Warning' }
)
const w = new Warning(7)

const pd = w.toProblemDetails('/limit', { retryAfter: 60, exceeded: true })

t.assert.deepStrictEqual(pd, {
type: 'https://example.net/probs/warn',
title: 'Warning',
status: 429,
detail: 'Threshold exceeded by 7',
instance: '/limit',
code: 'WARN',
details: { retryAfter: 60, exceeded: true }
})
})

test('title falls back to a generic label for unknown status codes', (t) => {
t.plan(2)

const E = createRFC9457Error('WEIRD', 'unusual status', 599)
const pd = new E().toProblemDetails()

t.assert.equal(pd.title, 'Unknown Error')
t.assert.equal(pd.status, 599)
})

test('toProblemDetails() falls back to the factory statusCode when the instance has none', (t) => {
t.plan(2)

// createError drops a falsy statusCode from the instance
const E = createRFC9457Error('CODE', 'oops', 0)
const pd = new E().toProblemDetails()

t.assert.equal(pd.status, 0)
t.assert.equal(pd.title, 'Unknown Error')
})

test('toProblemDetails() honors an overridden instance statusCode', (t) => {
t.plan(2)

const E = createRFC9457Error('CODE', 'oops', 500)
const e = new E()
e.statusCode = 502
const pd = e.toProblemDetails()

t.assert.equal(pd.status, 502)
t.assert.equal(pd.title, 'Bad Gateway')
})

test('created errors behave like regular fastify errors', (t) => {
t.plan(5)

const E = createRFC9457Error('CODE', 'hey %s', 400)
const err = new E('alice')

t.assert.ok(err instanceof Error)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.message, 'hey alice')
t.assert.equal(err.toString(), 'FastifyError [CODE]: hey alice')
})
55 changes: 55 additions & 0 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,63 @@ declare namespace createError {
readonly prototype: FastifyError & E
}

export interface RFC9457ErrorOptions {
type?: string
title?: string
}

export interface RFC9457ProblemDetails {
type: string
title: string
status: number
detail: string
instance: string
code: string
details: Record<string, unknown>
}

export interface RFC9457Error extends FastifyError {
toProblemDetails(instance?: string, details?: Record<string, unknown>): RFC9457ProblemDetails
}

export interface RFC9457ErrorConstructor<
E extends { code: string, statusCode?: number } = { code: string, statusCode?: number },
T extends unknown[] = [any?, any?, any?]
> {
new(...arg: T): RFC9457Error & E
(...arg: T): RFC9457Error & E
readonly prototype: RFC9457Error & E
}

export const FastifyError: FastifyErrorConstructor

export function createRFC9457Error<C extends string, SC extends number, Arg extends unknown[] = [any?, any?, any?]> (
code: C,
message: string,
statusCode: SC,
opts?: RFC9457ErrorOptions,
Base?: ErrorConstructor,
captureStackTrace?: boolean
): RFC9457ErrorConstructor<{ code: C, statusCode: SC }, Arg>

export function createRFC9457Error<C extends string, Arg extends unknown[] = [any?, any?, any?]> (
code: C,
message: string,
statusCode?: number,
opts?: RFC9457ErrorOptions,
Base?: ErrorConstructor,
captureStackTrace?: boolean
): RFC9457ErrorConstructor<{ code: C }, Arg>

export function createRFC9457Error<Arg extends unknown[] = [any?, any?, any?]> (
code: string,
message: string,
statusCode?: number,
opts?: RFC9457ErrorOptions,
Base?: ErrorConstructor,
captureStackTrace?: boolean
): RFC9457ErrorConstructor<{ code: string }, Arg>

export const createError: CreateError
export { createError as default }
}
Expand Down
48 changes: 47 additions & 1 deletion types/index.tst.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { expect } from 'tstyche'
import createError, { FastifyError, FastifyErrorConstructor } from '..'
import createError, { FastifyError, FastifyErrorConstructor, RFC9457Error, RFC9457ErrorConstructor, RFC9457ProblemDetails, createRFC9457Error } from '..'

const CustomError = createError('ERROR_CODE', 'message')
expect(CustomError).type.toBe<
Expand Down Expand Up @@ -151,3 +151,49 @@ if (error instanceof FastifyError) {
expect(error.message).type.toBe<string>()
expect(error.statusCode).type.toBe<number | undefined>()
}

const RFC9457CustomError = createRFC9457Error('ERROR_CODE', 'message')
expect(RFC9457CustomError).type.toBe<
RFC9457ErrorConstructor<{ code: 'ERROR_CODE' }>
>()
const rfc9457Err = new RFC9457CustomError()
expect(rfc9457Err).type.toBe<RFC9457Error & { code: 'ERROR_CODE' }>()
expect(rfc9457Err.code).type.toBe<'ERROR_CODE'>()
expect(rfc9457Err.message).type.toBe<string>()
expect(rfc9457Err.statusCode).type.toBe<number | undefined>()

const problemDetails = rfc9457Err.toProblemDetails('/path', { extra: 1 })
expect(problemDetails).type.toBe<RFC9457ProblemDetails>()
expect(problemDetails.type).type.toBe<string>()
expect(problemDetails.title).type.toBe<string>()
expect(problemDetails.status).type.toBe<number>()
expect(problemDetails.detail).type.toBe<string>()
expect(problemDetails.instance).type.toBe<string>()
expect(problemDetails.code).type.toBe<string>()
expect(problemDetails.details).type.toBe<Record<string, unknown>>()

const RFC9457TypedError = createRFC9457Error(
'OTHER_CODE',
'message',
400,
{ type: 'https://example.net/probs/other', title: 'Other' }
)
expect(RFC9457TypedError).type.toBe<
RFC9457ErrorConstructor<{ code: 'OTHER_CODE'; statusCode: 400 }>
>()
const rfc9457Typed = new RFC9457TypedError()
expect(rfc9457Typed).type.toBe<
RFC9457Error & { code: 'OTHER_CODE'; statusCode: 400 }
>()
expect(rfc9457Typed.statusCode).type.toBe<400>()

const RFC9457TypedArgError = createRFC9457Error<[string]>(
'ARG_CODE',
'expect %s message',
400
)
RFC9457TypedArgError('a')
expect(RFC9457TypedArgError).type.not.toBeCallableWith('a', 'b')
expect(RFC9457TypedArgError).type.not.toBeConstructableWith('a', 'b')
expect(RFC9457TypedArgError).type.not.toBeCallableWith(1)
expect(RFC9457TypedArgError).type.not.toBeConstructableWith(1)
Loading