From 56e84a2a3a74d5fe3b4ce0e16aa5dfd8c78d849d Mon Sep 17 00:00:00 2001 From: mrjvs Date: Thu, 14 Sep 2023 19:55:50 +0200 Subject: [PATCH] better error handling --- src/routes/index.ts | 9 ++++++++- src/utils/sending.ts | 11 +++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 src/utils/sending.ts diff --git a/src/routes/index.ts b/src/routes/index.ts index d4dba33..584fa32 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -6,7 +6,14 @@ export default defineEventHandler(async (event) => { // parse destination URL const destination = getQuery<{ destination?: string }>(event).destination; - if (!destination) throw new Error('invalid destination'); + if (!destination) + return sendJson({ + event, + status: 400, + data: { + error: 'destination query parameter invalid', + }, + }); // proxy await proxyRequest(event, destination, { diff --git a/src/utils/sending.ts b/src/utils/sending.ts new file mode 100644 index 0000000..2b882f0 --- /dev/null +++ b/src/utils/sending.ts @@ -0,0 +1,11 @@ +import { H3Event, EventHandlerRequest } from 'h3'; + +export function sendJson(ops: { + event: H3Event; + data: Record; + status?: number; +}) { + setResponseStatus(ops.event, ops.status ?? 200); + appendResponseHeader(ops.event, 'content-type', 'application/json'); + send(ops.event, JSON.stringify(ops.data, null, 2)); +}