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
5 changes: 5 additions & 0 deletions src/error/json-errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
type JsonError = SyntaxError;

export function isJsonParsingError(error: unknown): error is JsonError {
return error instanceof SyntaxError;
}
9 changes: 8 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { hostOptions } from "@/src/enviroment";
import {
errorHandler,
httpErrorHandler,
jsonParsingErrorHandler,
ormErrorHandler,
zodErrorHandler,
} from "@/src/middleware/error-middleware";
Expand Down Expand Up @@ -44,7 +45,13 @@ api.use("/teamapplications", teamApplicationRouter);
api.use("/teams", teamsRouter);

// Error handling
api.use(ormErrorHandler, zodErrorHandler, httpErrorHandler, errorHandler);
api.use(
jsonParsingErrorHandler,
ormErrorHandler,
zodErrorHandler,
httpErrorHandler,
errorHandler,
);

api.listen(hostOptions.port, () => {
console.info(
Expand Down
15 changes: 15 additions & 0 deletions src/middleware/error-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@ import { clientError, isHttpError, serverError } from "@/src/error/http-errors";
import { isOrmError } from "@/src/error/orm-error";
import type { ErrorRequestHandler } from "express";
import { isZodErrorLike } from "zod-validation-error";
import { isJsonParsingError } from "../error/json-errors";

export const jsonParsingErrorHandler: ErrorRequestHandler = (
err,
_req,
res,
next,
) => {
if (isJsonParsingError(err)) {
return res
.status(400)
.json({ error: true, message: `Invalid json: ${err.message}` });
}
next(err);
};

export const httpErrorHandler: ErrorRequestHandler = (err, _req, res, next) => {
if (isHttpError(err)) {
Expand Down