,

Utilizing Express Error Handler with Typescript

Posted by


In this tutorial, we will learn how to use the Express error handler with TypeScript in a Node.js application. Express error handler is a middleware function that helps to handle errors that occur during the execution of our application. It helps to centralize error handling logic and ensures that our application does not crash when an error occurs.

Step 1: Set up a TypeScript project
First, we need to set up a new TypeScript project. You can create a new directory for your project and run the following command in the terminal:

mkdir express-error-handler
cd express-error-handler
npm init -y
npm install express typescript @types/express
npx tsc --init

Step 2: Create an Express server
Next, create a new file called app.ts in the root directory of your project and add the following code to set up an Express server:

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

const app = express();

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Step 3: Create a custom error handler
Now, let’s create a custom error handler middleware function that will handle any errors that occur in our application. Create a new file called errorHandler.ts and add the following code:

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

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  console.error(err.stack);
  res.status(500).json({ message: 'Internal Server Error' });
};

Step 4: Import the error handler middleware in the server file
Next, import the error handler middleware function in the app.ts file and add it as the last middleware function in the Express application:

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

const app = express();

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
  res.send('Hello World!');
});

app.use(errorHandler);

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Step 5: Throw an error to test the error handler
Finally, let’s add a route handler that throws an error to test the error handler middleware function. Update the app.ts file with the following code:

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

const app = express();

app.use(express.json());

app.get('/', (req: Request, res: Response) => {
  res.send('Hello World!');
});

app.get('/error', (req: Request, res: Response, next: NextFunction) => {
  throw new Error('Something went wrong');
});

app.use(errorHandler);

app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Now, if you run the server using npx ts-node app.ts and navigate to http://localhost:3000/error, you should see the error message ‘Internal Server Error’ returned by the error handler middleware function.

That’s it! You have successfully set up an Express error handler with TypeScript in your Node.js application. Express error handler helps to centralize error handling logic and ensures that your application does not crash when an error occurs. Feel free to customize the error handler middleware function to suit your application’s needs.

0 0 votes
Article Rating

Leave a Reply

7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@codinginflow
2 hours ago

Get my FREE React Best Practices course: https://codinginflow.com/reactbestpractices

@itsLarryAlright
2 hours ago

How can you then throw errors in your services and handle it within routes?

@mayankjoshi2497
2 hours ago

Zod be like wtf

@Yalchin403
2 hours ago

This is kind of feeling wrong… You still need to have one main try and catch and call next() method for each case, I guess it would be better if we can just throw the error with defined status and message, and that should be all

@aniketbhalla1521
2 hours ago

Osm

@khuerustom_red6518
2 hours ago

for videos like this plz increase the size of the font.

@nourmorgan6751
2 hours ago

I miss your android videos 😢❤

7
0
Would love your thoughts, please comment.x
()
x