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

4

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

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay