TypeScript Express tutorial #3. Error handling and validating incoming data

Express JavaScript

This entry is part 3 of 7 in the TypeScript Express tutorial

Since not always everything goes perfectly, you need to expect the unexpected. To prepare for that, we cover TypeScript Express error handling and incoming data validation. Just as before, the repository for the tutorial is mwanago/express-typescript. If you find it helpful, feel free to give it a star.

Express Error handling

In the previous part of the tutorial, we wrote a handler function to return a post with a specific ID:

There is a slight problem with it though. If a post with a particular ID does not exist, its value in the callback function is null. We then send it, resulting in a response with a code 200 OK. It indicates that everything went fine and the user got a document that he requests, but this post is not empty in our database: it just does not exist. There is a big list of status codes that you can use, but in this case, we use 404 Not Found.

The 200 OK code if default when you use the send function. To change that, you need to call the status function, before using send.

Now when someone tries to access a post that does not exist, he is informed about what went wrong.

express error handling postman

This outcome is good, but we can make our code better. We want to create errors from our route handlers and let the middleware worry about sending them. There is a default error handler built into Express. To use it, you need to call the next function with an argument (other than the string ‘route’).

Handling the error in this way results in a 500 Internal Server Error and the error page is rendered.

express error handling default postman

If we want to handle it differently, we need to create our Express error handling middleware

Express Error handling middleware

First, let’s create a class that we are going to use to throw errors.


If  you would like to know more about the Error object and the errors in general, check out Handling errors in JavaScript with try…catch and finally

Defining Express error handling middleware is almost the same as any other middleware, except we use four arguments instead of three, with the error being the additional first argument.


Since Express runs all the middleware from the first to the last, your error handlers should be at the end of your application stack. If you pass the error to the next function, the framework omits all the other middleware in the chain and skips straight to the error handling middleware which is recognized by the fact that it has four arguments.

The last thing to do is to attach the error handling middleware to our app:


We can use the HttpException in the same manner when a post that the user wants to delete or modify a post that doesn’t exist. That would mean creating the HttpException in the same way. To avoid redundant code, we can prepare an exception just for that situation.


Validating incoming data

Another thing worth mentioning is validating input data to prevent the users from creating invalid documents in our collections. To do that I use a package called class-validator with an additional middleware.

The first thing to do is to create a data transfer object (DTO) file that carries data between our functions. It contains specification on how should the incoming data look.


To use decorators with TypeScript, you need to add   to your

When we got that down, the only thing left is the validation middleware. Since the body of our request is a plain object, we need to transform it into our class first. To do that, I use the class-transformer package.


The class-validator package validates the object, and if it finds some errors, the middleware calls the next function with the error details. Since we pass an error into the next function, the Express error middleware that we described above takes care of it. The errors variable keeps an array of errors, each of them having the constraints object with the details. This simple example creates a string of all of the issues.

The 400 Bad Request status code means that there is something wrong with the request that the client sent.

If you need to, you can also pass an array so that it can be easier to iterate over on the frontend

A thing left to do is to attach the middleware:

Since we want it only on some of our endpoints, we attach it straight before the handler functions. In the example above, the middleware validates the data before the   function runs.

Validating the PATCH handler data

It would be great to use that validation in our updating logic too. There is a small catch: in our CreatePostDto class, all fields are required, and we are using HTTP PATCH that allows for updating just some of the properties without passing the rest of them. There is an easy solution for that thanks to the skipMissingProperties option.


It skips validating all the properties that are missing, so if you are updating just a part of the document, it doesn’t cause an error just because a required property is not present.


In this article, we’ve covered Typescript Express error handling. To do that we’ve created an Express error handling middleware and used the next function with an additional argument to pass the error to the error handling middleware. Aside from that, we’ve learned how to validate incoming data in our POST and PATCH handlers using the class-validator package. All those new skills will surely be useful, especially because the next part of the course will cover registering users and authentication.

Series Navigation<< TypeScript Express tutorial #2. MongoDB, models and environment variablesTypeScript Express tutorial #4. Registering users and authenticating with JWT >>
Notify of