I wrote an error handler like this:
AppError class:
const getStatus = (statusCode) => {
if (statusCode >= 400 && statusCode < 500) return "fail";
return "error";
};
export class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
this.status = getStatus(statusCode);
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
and this is some of the error handler:
const sendErrorDev = (err, req, res) => {
console.log("dev", err);
return res.status(err.statusCode ?? 500).json({
status: err.status,
error: err,
message: err.message,
stack: err.stack,
});
};
const globalErrorHandler = (err, req, res, next) => {
console.log("Caught Error:", err.statusCode);
err.statusCode = err.statusCode || 500;
err.status = err.status || "error";
if (process.env.NODE_ENV === "development") {
console.log("env", process.env.NODE_ENV);
sendErrorDev(err, req, res);
} else if (process.env.NODE_ENV === "production") {
let error = cloneError(err);
// Map known error types
error = handleError(error);
// MongoDB duplicate key errors (code 11000)
if (error.code === 11000) error = handleDuplicateFieldDB(error);
sendErrorProd(error, req, res);
}
};
export default globalErrorHandler;
I am using this for login and I send the error like this:
if (!user || !(await user.correctPassword(password, user.password))) {
return next(new AppError("Incorrect email or password", 401));
}
I get an error in postman 500 Internal Server Error
"status": "error",
"error": {
"code": "ERR_HTTP_INVALID_STATUS_CODE",
"statusCode": 500,
"status": "error"
},
"message": "Invalid status code: fail",
"stack": "RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: failn
The env is a dev env. The err.statusCode and err.status are for some reason undefined in the globalErrorHandler.
If I change the this.status in the AppError to 401 (this.status=401) I get my error but the error in postman remains 500 Internal Server Error and the err.status and err.statusCode are not printed from globalErrorHandler so it doesn’t even enter the function.
I am very confused, please help.
Thank you