Skip to content

Commit

Permalink
error handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
Nguyen-Duc-Khai committed Nov 27, 2023
1 parent fca177d commit 193df19
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
28 changes: 28 additions & 0 deletions backend/src/middlewares/errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const httpStatus = require("http-status");
const { isCelebrateError } = require("celebrate");

const errorHandler = (err, req, res, next) => {
if (!isCelebrateError(err)) {
let { statusCode, message } = err;
if (!err.isOperational) {
statusCode = httpStatus.INTERNAL_SERVER_ERROR;
message = httpStatus[httpStatus.INTERNAL_SERVER_ERROR];
}

res.locals.errorMessage = err.message;

const response = {
statusCode,
message,
stack: err.stack,
};

res.status(statusCode).send(response);
} else {
next(err);
}
};

module.exports = {
errorHandler,
};
22 changes: 22 additions & 0 deletions backend/src/utils/ApiError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class ApiError extends Error {
constructor(
statusCode,
message,
errorEnum,
isOperational = true,
stack = ""
) {
super();
this.statusCode = statusCode;
this.isOperational = isOperational;
this.message = message;
this.errorEnum = errorEnum;
if (stack) {
this.stack = stack;
} else {
Error.captureStackTrace(this, this.constructor);
}
}
}

module.exports = ApiError;

0 comments on commit 193df19

Please sign in to comment.