Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

types: add generics to H3Error data and createError #566

Merged
merged 4 commits into from
Nov 20, 2023
Merged
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
18 changes: 10 additions & 8 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@
* @property {string} statusMessage - A string representing the HTTP status message.
* @property {boolean} fatal - Indicates if the error is a fatal error.
* @property {boolean} unhandled - Indicates if the error was unhandled and auto captured.
* @property {any} data - An extra data that will be included in the response.
* @property {DataT} data - An extra data that will be included in the response.
* This can be used to pass additional information about the error.
* @property {boolean} internal - Setting this property to `true` will mark the error as an internal error.
*/
export class H3Error extends Error {
export class H3Error<DataT = any> extends Error {
static __h3_error__ = true;
statusCode = 500;
fatal = false;
unhandled = false;
statusMessage?: string;
data?: any;
data?: DataT;
cause?: unknown;

constructor(message: string, opts: { cause?: unknown } = {}) {
Expand All @@ -40,7 +40,7 @@

toJSON() {
const obj: Pick<
H3Error,
H3Error<DataT>,

Check warning on line 43 in src/error.ts

View check run for this annotation

Codecov / codecov/patch

src/error.ts#L43

Added line #L43 was not covered by tests
"message" | "statusCode" | "statusMessage" | "data"
> = {
message: this.message,
Expand All @@ -64,18 +64,20 @@
* @param input {string | (Partial<H3Error> & { status?: number; statusText?: string })} - The error message or an object containing error properties.
* @return {H3Error} - An instance of H3Error.
*/
export function createError(
input: string | (Partial<H3Error> & { status?: number; statusText?: string }),
export function createError<DataT = any>(
input:
| string
| (Partial<H3Error<DataT>> & { status?: number; statusText?: string }),
): H3Error {
if (typeof input === "string") {
return new H3Error(input);
return new H3Error<DataT>(input);

Check warning on line 73 in src/error.ts

View check run for this annotation

Codecov / codecov/patch

src/error.ts#L73

Added line #L73 was not covered by tests
}

if (isError(input)) {
return input;
}

const err = new H3Error(input.message ?? input.statusMessage ?? "", {
const err = new H3Error<DataT>(input.message ?? input.statusMessage ?? "", {
cause: input.cause || input,
});

Expand Down