Error Handling - Fullstack Application

2 Minutes

charlie beemy profile picture
By
  • code
  • fullstack
  • error handling
Error x icon and Javascript Icon - pofo

General error handling patterns for your full-stack application.

When communicating with a server, there is always a chance the response will not be as expected even if the client and server input match. Because of this, it's important to handle any potential errors that might occur when communicating with a server.

Where to handle errors? 

Errors should be handled both on the server and client side.

Server Errors

For the server, it might make sense to display a warning message in the console (or on any custom error reporting system) so that it becomes easier to identify where a majority of server failures are coming from. Your endpoint might looks something like this:

This handles the rare occurrence that faulty server code gets pushed to production.

For any requests that result in failure due to not being able to find the resource, I actually prefer to not return a server error message. This makes the server code simpler and it makes sense since we are going to need to handle errors on the client anyways.

Client Errors

After we make a fetch, we need to:

  1. Make sure the server did not return a error message.

  2. Make sure the the request operation was successful.

In my request function, I will purposely throw an error if either of these conditions is met. However, this means that we have to catch the error when we call the function. It would look something like this:

Displaying Errors Messages

If you are using typescript, you will get yelled at for assuming that an error instance is thrown when catching errors. This is because in javascript, you are can throw any type of variable. As a result, I coded a handy function to handle this:

Now, when we need to display any error messages to the user, we can call this function:

Made with