From 0eb97f0df6e5a443ae0abdaae39e3a3ea2859d2b Mon Sep 17 00:00:00 2001 From: Ott Martens Date: Sun, 12 Nov 2023 10:15:55 +0200 Subject: [PATCH] Add error handling --- index.ts | 52 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/index.ts b/index.ts index 6ec8ba2..3923cc4 100644 --- a/index.ts +++ b/index.ts @@ -20,29 +20,41 @@ async function handle(request: Request) { case '/callback': return await fetchAccessToken(params); } + + return new Response(); } async function fetchAccessToken(requestParams: URLSearchParams) { - const code = requestParams.get('code'); - - const response = await fetch('https://github.com/login/oauth/access_token', { - method: 'POST', - headers: { - 'content-type': 'application/json', - 'user-agent': 'decap-cms-github-oauth-api-cloudflare', - accept: 'application/json', - }, - body: JSON.stringify({ client_id, client_secret, code }), - }).then((res) => res.json()); - - const loginResponse = decapCMSLoginScript(response.access_token); - - return new Response(loginResponse, { - status: 201, - headers: { - 'Content-Type': 'text/html;charset=UTF-8', - }, - }); + try { + const code = requestParams.get('code'); + + const response = await fetch( + 'https://github.com/login/oauth/access_token', + { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'user-agent': 'decap-cms-github-oauth-api-cloudflare', + accept: 'application/json', + }, + body: JSON.stringify({ client_id, client_secret, code }), + } + ).then((res) => res.json()); + + const loginResponse = decapCMSLoginScript(response.access_token); + + return new Response(loginResponse, { + status: 201, + headers: { + 'Content-Type': 'text/html;charset=UTF-8', + }, + }); + } catch (err) { + console.error(err); + return new Response(err.message, { + status: 500, + }); + } } function redirectToAuthFlow() {