Skip to content

Commit

Permalink
feat!: 请求失败时抛出异常
Browse files Browse the repository at this point in the history
  • Loading branch information
otakustay committed Sep 3, 2022
1 parent bafc42d commit 49776c9
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
14 changes: 14 additions & 0 deletions src/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export class RequestError extends Error {
readonly statusCode: number;
readonly headers: Record<string, string>;
readonly body: string;

constructor(statusCode: number, headers: Record<string, string>, body: string) {
super(`Request failed with status code ${statusCode}`);
this.statusCode = statusCode;
this.headers = headers;
this.body = body;
}
}

export const isRequestError = (error: unknown): error is RequestError => error instanceof RequestError;
14 changes: 10 additions & 4 deletions src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {ReadableStream} from 'node:stream/web';
import {BodyInit, fetch} from 'undici';
import {fromPairs} from 'ramda';
import {Authorization, BceCredential} from './authorization';
import {RequestError} from './error';

const stringifyDate = (date: Date) => date.toISOString().replace(/\.\d+Z$/, 'Z');

Expand Down Expand Up @@ -105,9 +106,14 @@ export class Http {
body: options.body,
}
);
return {
response,
headers: fromPairs([...response.headers.entries()]),
};

const responseHeaders = fromPairs([...response.headers.entries()]);

if (response.ok) {
return {headers: responseHeaders, response};
}

const body = await response.text();
throw new RequestError(response.status, responseHeaders, body);
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export {BceCredential} from './authorization';
export * from './error';
export * from './bls';
export * from './bos';

0 comments on commit 49776c9

Please sign in to comment.