Skip to content

💥 Make UnexpectedResponseError have Request and Response #96

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

Merged
merged 1 commit into from
Dec 24, 2022
Merged
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
37 changes: 27 additions & 10 deletions rest/error.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import type { ErrorLike } from "../deps/scrapbox-rest.ts";
import { tryToErrorLike } from "../is.ts";

/** 想定されない応答が帰ってきたときに投げる例外 */
export class UnexpectedResponseError extends Error {
name = "UnexpectedResponseError";
status: number;
statusText: string;
body: string;
path: URL;
request: Request;
response: Response;

constructor(
init: { status: number; statusText: string; body: string; path: URL },
init: { request: Request; response: Response },
) {
super(
`${init.status} ${init.statusText} when fetching ${init.path.toString()}`,
`${init.response.status} ${init.response.statusText} when fetching ${init.request.url}`,
);

this.status = init.status;
this.statusText = init.statusText;
this.body = init.body;
this.path = init.path;
this.request = init.request.clone();
this.response = init.response.clone();

// @ts-ignore only available on V8
if (Error.captureStackTrace) {
Expand All @@ -24,3 +24,20 @@ export class UnexpectedResponseError extends Error {
}
}
}

/** 失敗した要求からエラー情報を取り出す */
export const makeError = async <T extends ErrorLike>(
req: Request,
res: Response,
): Promise<{ ok: false; value: T }> => {
const response = res.clone();
const text = await response.text();
const value = tryToErrorLike(text);
if (!value) {
throw new UnexpectedResponseError({ request: req, response });
}
return {
ok: false,
value: value as T,
};
};
28 changes: 10 additions & 18 deletions rest/getGyazoToken.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { NotLoggedInError } from "../deps/scrapbox-rest.ts";
import { cookie } from "./auth.ts";
import { UnexpectedResponseError } from "./error.ts";
import { tryToErrorLike } from "../is.ts";
import { makeError } from "./error.ts";
import { BaseOptions, Result, setDefaults } from "./util.ts";

export interface GetGyazoTokenOptions extends BaseOptions {
Expand All @@ -26,26 +25,19 @@ export const getGyazoToken = async (
>
> => {
const { sid, hostName, gyazoTeamsName } = setDefaults(init ?? {});
const path = `https://${hostName}/api/login/gyazo/oauth-upload/token${
gyazoTeamsName ? `?gyazoTeamsName=${gyazoTeamsName}` : ""
}`;

const res = await fetch(
path,
const req = new Request(
`https://${hostName}/api/login/gyazo/oauth-upload/token${
gyazoTeamsName ? `?gyazoTeamsName=${gyazoTeamsName}` : ""
}`,
sid ? { headers: { Cookie: cookie(sid) } } : undefined,
);

const res = await fetch(req);
if (!res.ok) {
const text = await res.text();
const value = tryToErrorLike(text);
if (!value) {
throw new UnexpectedResponseError({
path: new URL(path),
...res,
body: await res.text(),
});
}
return { ok: false, value: value as NotLoggedInError };
return makeError<NotLoggedInError>(
req,
res,
);
}

const { token } = (await res.json()) as { token?: string };
Expand Down
31 changes: 11 additions & 20 deletions rest/getSnapshots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ import type {
PageSnapshot,
Snapshot,
} from "../deps/scrapbox-rest.ts";
import { tryToErrorLike } from "../is.ts";
import { cookie } from "./auth.ts";
import { BaseOptions, Result, setDefaults } from "./util.ts";
import { UnexpectedResponseError } from "./error.ts";
import { makeError } from "./error.ts";

/** 不正なfollowingIdを渡されたときに発生するエラー */
export interface InvalidPageSnapshotIdError extends ErrorLike {
Expand Down Expand Up @@ -39,15 +38,16 @@ export const getSnapshots = async (
>
> => {
const { sid, hostName, fetch, followingId } = setDefaults(options ?? {});
const path = `https://${hostName}/api/page-snapshots/${project}/${pageId}/${
followingId ? `?followingId=${followingId}` : ""
}`;

const res = await fetch(
path,
const req = new Request(
`https://${hostName}/api/page-snapshots/${project}/${pageId}/${
followingId ? `?followingId=${followingId}` : ""
}`,
sid ? { headers: { Cookie: cookie(sid) } } : undefined,
);

const res = await fetch(req);

if (!res.ok) {
if (res.status === 422) {
return {
Expand All @@ -58,19 +58,10 @@ export const getSnapshots = async (
},
};
}
const text = await res.text();
const value = tryToErrorLike(text);
if (!value) {
throw new UnexpectedResponseError({
path: new URL(path),
...res,
body: text,
});
}
return {
ok: false,
value: value as (NotFoundError | NotLoggedInError | NotMemberError),
};
return makeError<NotFoundError | NotLoggedInError | NotMemberError>(
req,
res,
);
}

const data = (await res.json()) as PageSnapshot;
Expand Down
31 changes: 8 additions & 23 deletions rest/getTweetInfo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import type {
TweetInfo,
} from "../deps/scrapbox-rest.ts";
import { cookie, getCSRFToken } from "./auth.ts";
import { UnexpectedResponseError } from "./error.ts";
import { tryToErrorLike } from "../is.ts";
import { makeError } from "./error.ts";
import { ExtendedOptions, Result, setDefaults } from "./util.ts";

/** 指定したTweetの情報を取得する
Expand All @@ -27,12 +26,10 @@ export const getTweetInfo = async (
>
> => {
const { sid, hostName, fetch, csrf } = setDefaults(init ?? {});
const path = `https://${hostName}/api/embed-text/twitter?url=${
encodeURIComponent(url.toString())
}`;

const res = await fetch(
path,
const req = new Request(
`https://${hostName}/api/embed-text/twitter?url=${
encodeURIComponent(url.toString())
}`,
{
method: "POST",
headers: {
Expand All @@ -44,6 +41,8 @@ export const getTweetInfo = async (
},
);

const res = await fetch(req);

if (!res.ok) {
if (res.status === 422) {
return {
Expand All @@ -54,21 +53,7 @@ export const getTweetInfo = async (
},
};
}
const text = await res.text();
const value = tryToErrorLike(text);
if (!value) {
throw new UnexpectedResponseError({
path: new URL(path),
...res,
body: text,
});
}
return {
ok: false,
value: value as
| SessionError
| BadRequestError,
};
return makeError<SessionError | BadRequestError>(req, res);
}

const tweet = (await res.json()) as TweetInfo;
Expand Down
30 changes: 8 additions & 22 deletions rest/getWebPageTitle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import type {
SessionError,
} from "../deps/scrapbox-rest.ts";
import { cookie, getCSRFToken } from "./auth.ts";
import { UnexpectedResponseError } from "./error.ts";
import { tryToErrorLike } from "../is.ts";
import { makeError } from "./error.ts";
import { ExtendedOptions, Result, setDefaults } from "./util.ts";

/** 指定したURLのweb pageのtitleをscrapboxのserver経由で取得する
Expand All @@ -26,12 +25,11 @@ export const getWebPageTitle = async (
>
> => {
const { sid, hostName, fetch, csrf } = setDefaults(init ?? {});
const path = `https://${hostName}/api/embed-text/url?url=${
encodeURIComponent(url.toString())
}`;

const res = await fetch(
path,
const req = new Request(
`https://${hostName}/api/embed-text/url?url=${
encodeURIComponent(url.toString())
}`,
{
method: "POST",
headers: {
Expand All @@ -43,6 +41,8 @@ export const getWebPageTitle = async (
},
);

const res = await fetch(req);

if (!res.ok) {
if (res.status === 422) {
return {
Expand All @@ -53,21 +53,7 @@ export const getWebPageTitle = async (
},
};
}
const text = await res.text();
const value = tryToErrorLike(text);
if (!value) {
throw new UnexpectedResponseError({
path: new URL(path),
...res,
body: text,
});
}
return {
ok: false,
value: value as
| SessionError
| BadRequestError,
};
return makeError<SessionError | BadRequestError>(req, res);
}

const { title } = (await res.json()) as { title: string };
Expand Down
27 changes: 10 additions & 17 deletions rest/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import type {
SearchedTitle,
} from "../deps/scrapbox-rest.ts";
import { cookie } from "./auth.ts";
import { UnexpectedResponseError } from "./error.ts";
import { tryToErrorLike } from "../is.ts";
import { makeError } from "./error.ts";
import { BaseOptions, Result, setDefaults } from "./util.ts";

/** 不正なfollowingIdを渡されたときに発生するエラー */
Expand All @@ -33,15 +32,16 @@ export const getLinks = async (
}, NotFoundError | NotLoggedInError | InvalidFollowingIdError>
> => {
const { sid, hostName, fetch, followingId } = setDefaults(options ?? {});
const path = `https://${hostName}/api/pages/${project}/search/titles${
followingId ? `?followingId=${followingId}` : ""
}`;

const res = await fetch(
path,
const req = new Request(
`https://${hostName}/api/pages/${project}/search/titles${
followingId ? `?followingId=${followingId}` : ""
}`,
sid ? { headers: { Cookie: cookie(sid) } } : undefined,
);

const res = await fetch(req);

if (!res.ok) {
if (res.status === 422) {
return {
Expand All @@ -52,17 +52,10 @@ export const getLinks = async (
},
};
}
const text = await res.text();
const value = tryToErrorLike(text);
if (!value) {
throw new UnexpectedResponseError({
path: new URL(path),
...res,
body: text,
});
}
return { ok: false, value: value as NotFoundError | NotLoggedInError };

return makeError<NotFoundError | NotLoggedInError>(req, res);
}

const pages = (await res.json()) as SearchedTitle[];
return {
ok: true,
Expand Down
Loading