Add basic error handling

+ Add express-async-errors package to handle async errors
+ Add ForwaradableError class (Base class for all project-specific errors)
+ Add defaultErrorHandler middleware which handles errors and sends info to the client
This commit is contained in:
Stephan
2022-04-28 14:39:16 +02:00
parent 4a65dd4665
commit 382a42d439
4 changed files with 60 additions and 0 deletions
+1
View File
@@ -27,6 +27,7 @@
"argon2": "^0.28.2",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"jsonwebtoken": "^8.5.1",
"nodemailer": "^6.7.0",
"redis": "^3.1.2"
+16
View File
@@ -0,0 +1,16 @@
export default class ForwardableError extends Error {
// If in different context
private readonly __id = "CUSTOM_ERROR";
public readonly status: number;
constructor(status: number, message: string) {
super(message);
this.status = status;
}
static isForwardableError(error: any): error is ForwardableError {
return error.__id === "CUSTOM_ERROR";
}
}
+36
View File
@@ -0,0 +1,36 @@
import { PrismaClientUnknownRequestError } from "@prisma/client/runtime";
import { NextFunction, Request, Response } from "express";
import ForwardableError from "./ForwardableError";
const env = process.env.NODE_ENV || "production";
export default function defaultErrorHandler(err: any, req: Request, res: Response, next: NextFunction) {
if (ForwardableError.isForwardableError(err)) {
return res.status(err.status).json({
type: "error",
payload: {
message: err.message,
...(env === "development"
? {
stack: err.stack,
}
: {}),
},
});
}
if (err instanceof PrismaClientUnknownRequestError) {
return res.status(404).json({
type: "error",
payload: {
message: "An unknown error occured. This could be due to malformed IDs",
...(env === "development"
? {
prisma: err.message,
stack: err.stack,
}
: {}),
},
});
}
}
+7
View File
@@ -6,6 +6,10 @@ import argon2 from "argon2";
import adminRouter from "./Routes/admin.routes";
import organisationRouter from "./Routes/organisation.routes";
import groupRouter from "./Routes/group.routes";
import defaultErrorHandler from "./Middleware/error/handler";
// Set up async error handling
require("express-async-errors");
require("dotenv").config(); // Load dotenv config
@@ -52,6 +56,9 @@ async function main() {
app.use("/api/groups", groupRouter);
// Error handling
app.use(defaultErrorHandler);
app.listen(process.env.PORT, () => {
console.log(`Listening on Port: ${process.env.PORT}`);
});