Skip to content
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
24 changes: 23 additions & 1 deletion src/api/json.ts
Original file line number Diff line number Diff line change
@@ -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 });
}

Expand All @@ -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";
}
4 changes: 2 additions & 2 deletions src/api/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
};
}
8 changes: 4 additions & 4 deletions src/api/notes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand All @@ -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);
}
}
4 changes: 2 additions & 2 deletions src/api/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down