diff --git a/src/api/json.ts b/src/api/json.ts index 5e675daff..c11327cce 100644 --- a/src/api/json.ts +++ b/src/api/json.ts @@ -1,6 +1,15 @@ import type { Response } from "express"; -export function respondWithError(res: Response, code: number, message: string) { +export function respondWithError( + res: Response, + code: number, + message: string, + logError?: unknown, +) { + if (logError) { + console.log(errStringFromError(logError)); + } + respondWithJSON(res, code, { error: message }); } @@ -13,3 +22,16 @@ export function respondWithJSON(res: Response, code: number, payload: unknown) { res.status(code).send(body); res.end(); } + +function errStringFromError(err: unknown): string { + if (typeof err === "string") { + return err; + } + if (err instanceof Error) { + return err.message; + } + if (err) { + return String(err); + } + return "An unknown error occurred"; +} diff --git a/src/api/middleware.ts b/src/api/middleware.ts index f75f2974d..0d6d0d221 100644 --- a/src/api/middleware.ts +++ b/src/api/middleware.ts @@ -22,8 +22,8 @@ export function middlewareAuth( } handler(req, res, user); - } catch { - respondWithError(res, 500, "Couldn't authenticate user"); + } catch (err) { + respondWithError(res, 500, "Couldn't authenticate user", err); } }; } diff --git a/src/api/notes.ts b/src/api/notes.ts index cb50f0f32..2191cdd0c 100644 --- a/src/api/notes.ts +++ b/src/api/notes.ts @@ -8,8 +8,8 @@ export async function handlerNotesGet(req: Request, res: Response, user: User) { try { const posts = await getNotesForUser(user.id); respondWithJSON(res, 200, posts); - } catch { - respondWithError(res, 500, "Couldn't retrieve notes"); + } catch (err) { + respondWithError(res, 500, "Couldn't retrieve notes", err); } } @@ -32,7 +32,7 @@ export async function handlerNotesCreate( const createdNote = await getNote(noteId); respondWithJSON(res, 201, createdNote); - } catch { - respondWithError(res, 500, "Couldn't create note"); + } catch (err) { + respondWithError(res, 500, "Couldn't create note", err); } } diff --git a/src/api/users.ts b/src/api/users.ts index 8cb4806ed..f10cf55c6 100644 --- a/src/api/users.ts +++ b/src/api/users.ts @@ -24,8 +24,8 @@ export async function handlerUsersCreate(req: Request, res: Response) { } else { respondWithError(res, 500, "Couldn't retrieve user"); } - } catch { - respondWithError(res, 500, "Couldn't create user"); + } catch (err) { + respondWithError(res, 500, "Couldn't create user", err); } }