skip to Main Content

I’ve tried all the ways to handle my errors but error handling middleware is never been called.

I tried many ways to handle the error but it seems that code instantly breaks when I throw an error.

-- App.js --
const app = express();
app.set('trust proxy', true); 
app.use(json());

app.use(
  cookieSession({
    signed: false, 
    secure: process.env.NODE_ENV !== 'test',
  })
);

// routes
app.use(CurrentUserRoute);
app.use(SignInRoute);
app.use(SignUpRoute);
app.use(SignOutRoute);

app.all('*', async (req, res) => {
  console.log('This is a global error handler at route level....');
  throw new Error('Error');
});

app.use(errorHandler);  // this is the error middleware

Error handling middleware:

import { Request, Response, NextFunction } from 'express';

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  console.log('Something went wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!: ', err);

  res.status(400).send({
    message: 'Something Went Wrong',
  });
};

In my routes, whenever I throw an error, the middleware is never called and it instantly shows its own error like

[auth] Error: "email" length must be at least 5 characters long
[auth] at /app/src/routes/signUp.ts:17:11
[auth] at step (/app/src/routes/signUp.ts:33:23)
[auth] at Object.next (/app/src/routes/signUp.ts:14:53)
[auth] at /app/src/routes/signUp.ts:8:71
[auth] at new Promise ()
[auth] at __awaiter (/app/src/routes/signUp.ts:4:12)
[auth] at /app/src/routes/signUp.ts:11:68
[auth] at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
[auth] at next (/app/node_modules/express/lib/router/route.js:137:13)
[auth] at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
[auth] at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
[auth] at /app/node_modules/express/lib/router/index.js:281:22
[auth] at Function.process_params (/app/node_modules/express/lib/router/index.js:335:12)
[auth] at next (/app/node_modules/express/lib/router/index.js:275:10)
[auth] at Function.handle (/app/node_modules/express/lib/router/index.js:174:3)
[auth] at router (/app/node_modules/express/lib/router/index.js:47:12)
[auth] [ERROR] 12:13:25 Error: "email" length must be at least 5 characters long

P.S I’m using Docker and Kubernetes Environment with ingress-nginx service but I don’t think it could have any problem with error handling.

2

Answers


  1. One of the ways to fix this problem is to make middleware directly in your app.js file.
    so instead of this :

    app.use(errorHandler);
    

    use this :

    app.use(async (error, req, res, next)=>{
    
         res.status(400).send({
              message: 'Something Went Wrong',
         });
    
    });
    
    Login or Signup to reply.
  2. if Error handling middleware don’t have any error you can use like this in controller

    use return next() after that error middleware should run

    const MyFunction = async (req, res, next) => {
        const error = new Error("Error Message in controller")
        return next(error);
    }
    

    my error middleware handling (errorMiddleware.js)

    const errorHandler = (err, req, res, next) => {
      console.log("Something went wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!: ", err);
    
      res.status(400).send({
        message: "Something Went Wrong",
      });
    };
    
    exports.errorHandler = errorHandler
    

    in app.js

    const {errorHandler} = require('./errorMiddleware');
    app.use(errorHandler); 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search