I am trying to handle errors with express with error middleware. This is my index:
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
require("dotenv").config();
const methodOverride = require('method-override')
const {logErrors, errorHandler,boomErrorHandler, error404Handler } = require("./src/middlewares/error.handler")
//modulos personalizados
const { productsRoutes } = require("./src/products/products.routes");
const userRoutes = require("./src/users/user.routes");
const UserServices = require("./src/users/user.services")
//nombre
const userService = new UserServices
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cors({ origin: true }));
app.use(methodOverride());
app.use(logErrors);
app.use(boomErrorHandler);
app.use(errorHandler);
// app.use(error404Handler);
exports.setCustomerClaim = functions.auth
.user()
.onCreate(userService.customerClaimServ)
productsRoutes(app);
exports.api = functions.https.onRequest(app);
As you can see I have logErrors middleware.
This is my simple controller which throws things fine but when I do a next()
inside the catch()
it doesn't get into the error middleware.
this is my controller:
async function getAll(req, res, next) {
try {
const products = await productServices.getAllSer();
console.log("Aca esta tu error");
res.json(products);
} catch (error) {
next();
}
}
this is my middleware:
/* eslint-disable @typescript-eslint/no-var-requires */
const boom = require("@hapi/boom");
function logErrors(err, req, res, next) {
console.error(err);
next(err);
}
function errorHandler(err, req, res, next) {
if (err) {
res.status(409).json({
message: err.message,
stack: err.stack,
});
} else {
next(err);
}
}
function boomErrorHandler(err, req, res, next) {
if (err.isBoom) {
const {output} = err;
res.status(output.statusCode).json(output.payload);
}
next(err);
}
function error404Handler (req, res) {
res.status(404)
res.send ({
message: boom.notFound('el recurso que busca no existe')
})
}
module.exports= {
logErrors,
errorHandler,
boomErrorHandler,
error404Handler
};
The problem is, it is not getting into the error middleware because anything before the next() is working fine.
I would appreciate any help. Thanks in advance!
CodePudding user response:
Your problem is in the controller, use like this return next(error);
:
async function getAll(req, res, next) {
try {
const products = await productServices.getAllSer();
console.log("Aca esta tu error");
res.json(products);
} catch (error) {
return next(error);
}
}