Skip to content

Commit

Permalink
feat: add extra to HttpError instances
Browse files Browse the repository at this point in the history
  • Loading branch information
Lordfirespeed committed Nov 5, 2024
1 parent a8c8e0b commit 0e07aaf
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/cold-poets-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@otterhttp/errors": minor
---

feat: add `extra` to HttpError instances, intended for adding additional fields to JSON response payloads
6 changes: 6 additions & 0 deletions packages/errors/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,23 @@ import ModuleError from "module-error"

import { HttpStatus, type StatusCode, isValidStatusCode, statusMessages } from "./status-codes"

type ExtraLiteral = string | number | boolean | null | undefined | { [property: string]: ExtraLiteral } | ExtraLiteral[]

type ModuleErrorOptions = ConstructorParameters<typeof ModuleError>[1]
export type HttpErrorOptions = ModuleErrorOptions & {
statusCode?: StatusCode
statusMessage?: string
exposeMessage?: boolean
headers?: OutgoingHttpHeaders
extra?: Record<string, ExtraLiteral>
}

export abstract class HttpError extends ModuleError {
statusCode: StatusCode
statusMessage: string
exposeMessage: boolean
headers: OutgoingHttpHeaders
extra: Record<string, ExtraLiteral>

static {
HttpError.prototype.name = "HttpError"
Expand All @@ -36,12 +40,14 @@ export abstract class HttpError extends ModuleError {
if (options.statusMessage != null) this.statusMessage = options.statusMessage
if (options.exposeMessage != null) this.exposeMessage = options.exposeMessage
if (options.headers != null) this.headers = options.headers
if (options.extra != null) this.extra = options.extra
}

this.statusCode ??= HttpStatus.InternalServerError
this.statusMessage ??= statusMessages[this.statusCode]
this.exposeMessage ??= this.statusCode < 500
this.headers ??= {}
this.extra ??= {}
}
}

Expand Down

0 comments on commit 0e07aaf

Please sign in to comment.