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 }
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;
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}`));
})
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)