DEV Community

Cover image for Typescript customized Function handler for exceptions with Node.js and Express.js
Luiz Calaça
Luiz Calaça

Posted on

Typescript customized Function handler for exceptions with Node.js and Express.js

Hi, Devs!

First of all, step one is to build the function handler for exceptions, it is necessary because when you use the throw the application's is going to broke, so when you use the try/catch scope and into catch we could use the method below to get the exception.

/middlewares/ErrorHandler.ts

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

class ErrorHandler {

    public static handle(error: Error, _req: Request, res: Response, next: NextFunction) {
        res.status(500).json({ message: error.message });
        next()
    }
}

export { ErrorHandler }
Enter fullscreen mode Exit fullscreen mode

Let's create the app.ts:

/src/app.ts

import express from 'express';
import { ErrorHandler } from './middlewares/ErrorHandler';
import { NextFunction, Request, Response } from 'express';

const app = express();
app.use(express.json());
app.post('/handler', (req: Request, res: Request, next: NextFunction) => {
try{
  if(req.body.number < 0)
    throw new Error('Negative number!');
}catch(error: any) {
 next(error)
}
});
app.use(ErrorHandler.handle); // necessary to be the last middleware to get the exception.

export default app;
Enter fullscreen mode Exit fullscreen mode

Let' create server.ts file to start the API:

import app from './app';

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => 
     console.log(`Running server on port: ${PORT}`));
})
Enter fullscreen mode Exit fullscreen mode

If you pass a negative number for the body request you'll receive an exception and it will treat with the customized handler because the last middleware (ErrorHandler) will get it.

That's all!

Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Top comments (0)