Skip to content

Commit

Permalink
Merge pull request #307 from samchon/features/fetch
Browse files Browse the repository at this point in the history
Add `HttpError.toJSON()` method
  • Loading branch information
samchon authored Apr 13, 2023
2 parents 0d8c21a + 2ea6710 commit 02c99cf
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/fetcher/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@nestia/fetcher",
"version": "1.0.1",
"version": "1.1.0-dev.20230413",
"description": "Fetcher library of Nestia SDK",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
Expand Down
41 changes: 41 additions & 0 deletions packages/fetcher/src/HttpError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
* @author Jeongho Nam - https://github.com/samchon
*/
export class HttpError extends Error {
/**
* @internal
*/
private body_: any = NOT_YET;

/**
* Initializer Constructor.
*
Expand All @@ -27,4 +32,40 @@ export class HttpError extends Error {
if (Object.setPrototypeOf) Object.setPrototypeOf(this, proto);
else (this as any).__proto__ = proto;
}

/**
* `HttpError` to JSON.
*
* When you call `JSON.stringify()` function on current `HttpError` instance,
* this `HttpError.toJSON()` method would be automatically called.
*
* Also, if response body from the remote HTTP server forms a JSON object,
* this `HttpError.toJSON()` method would be useful because it returns the
* parsed JSON object about the {@link message} property.
*
* @template T Expected type of the response body.
* @returns JSON object of the `HttpError`.
*/
public toJSON<T>(): HttpError.IProps<T> {
if (this.body_ === NOT_YET) this.body_ = JSON.parse(this.message);
return {
method: this.method,
path: this.path,
status: this.status,
message: this.body_,
};
}
}
export namespace HttpError {
/**
* Returned type of {@link HttpError.toJSON} method.
*/
export interface IProps<T> {
method: "GET" | "DELETE" | "POST" | "PUT" | "PATCH";
path: string;
status: number;
message: T;
}
}

const NOT_YET = {} as any;

0 comments on commit 02c99cf

Please sign in to comment.