From ed742d6d322d4d5116c54f62426f2f3cf0299b26 Mon Sep 17 00:00:00 2001 From: anatolykopyl Date: Sun, 4 Feb 2024 13:48:24 +0300 Subject: [PATCH] Better error handling --- index.ts | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/index.ts b/index.ts index fcbc8d4..d761c3d 100644 --- a/index.ts +++ b/index.ts @@ -6,7 +6,15 @@ const server = Bun.serve({ port: PORT, async fetch(req) { if (!req.body) { - throw new Error("No body provided"); + return new Response( + 'Bad request', + { + status: 400, + headers: { + "Content-Type": "text/html", + }, + } + ) } const submittedData = await req.json(); @@ -17,21 +25,26 @@ const server = Bun.serve({ ${JSON.stringify(submittedData, null, 2)} \`\`\``) - await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage?chat_id=${CHAT_ID}&text=${text}&parse_mode=markdown`) + try { + await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendMessage?chat_id=${CHAT_ID}&text=${text}&parse_mode=markdown`) + } catch (error) { + return new Response( + 'Internal server error', + { + status: 500, + headers: { + "Content-Type": "text/html", + }, + } + ) + } return new Response('success', { headers: { 'Access-Control-Allow-Origin': '*' } }); - }, - error(error) { - return new Response(`
${error}\n${error.stack}
`, { - headers: { - "Content-Type": "text/html", - }, - }); - }, -}); + } +}) console.log(`Listening on http://localhost:${server.port}...`);