Skip to content

Commit 395807f

Browse files
committed
Refactor error handling
1 parent 9f07b39 commit 395807f

File tree

4 files changed

+31
-9
lines changed

4 files changed

+31
-9
lines changed

src/api/json.ts

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
import type { Response } from "express";
22

3-
export function respondWithError(res: Response, code: number, message: string) {
3+
export function respondWithError(
4+
res: Response,
5+
code: number,
6+
message: string,
7+
logError?: unknown,
8+
) {
9+
if (logError) {
10+
console.log(errStringFromError(logError));
11+
}
12+
413
respondWithJSON(res, code, { error: message });
514
}
615

@@ -13,3 +22,16 @@ export function respondWithJSON(res: Response, code: number, payload: unknown) {
1322
res.status(code).send(body);
1423
res.end();
1524
}
25+
26+
function errStringFromError(err: unknown): string {
27+
if (typeof err === "string") {
28+
return err;
29+
}
30+
if (err instanceof Error) {
31+
return err.message;
32+
}
33+
if (err) {
34+
return String(err);
35+
}
36+
return "An unknown error occurred";
37+
}

src/api/middleware.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ export function middlewareAuth(
2222
}
2323

2424
handler(req, res, user);
25-
} catch {
26-
respondWithError(res, 500, "Couldn't authenticate user");
25+
} catch (err) {
26+
respondWithError(res, 500, "Couldn't authenticate user", err);
2727
}
2828
};
2929
}

src/api/notes.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ export async function handlerNotesGet(req: Request, res: Response, user: User) {
88
try {
99
const posts = await getNotesForUser(user.id);
1010
respondWithJSON(res, 200, posts);
11-
} catch {
12-
respondWithError(res, 500, "Couldn't retrieve notes");
11+
} catch (err) {
12+
respondWithError(res, 500, "Couldn't retrieve notes", err);
1313
}
1414
}
1515

@@ -32,7 +32,7 @@ export async function handlerNotesCreate(
3232

3333
const createdNote = await getNote(noteId);
3434
respondWithJSON(res, 201, createdNote);
35-
} catch {
36-
respondWithError(res, 500, "Couldn't create note");
35+
} catch (err) {
36+
respondWithError(res, 500, "Couldn't create note", err);
3737
}
3838
}

src/api/users.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ export async function handlerUsersCreate(req: Request, res: Response) {
2424
} else {
2525
respondWithError(res, 500, "Couldn't retrieve user");
2626
}
27-
} catch {
28-
respondWithError(res, 500, "Couldn't create user");
27+
} catch (err) {
28+
respondWithError(res, 500, "Couldn't create user", err);
2929
}
3030
}
3131

0 commit comments

Comments
 (0)