Ensuring the capture of all errors within asynchronous express route handlers using async-await syntax

Imagine having a route set up like this:

app.get('/malfunction', (req, res) => {
  throw new Error('Malfunctioning!');
});

In this case, no response will be sent to clients.

However, you can include a middleware for handling all errors:

const errorMiddleware = (error, req, res, next) => {
  if (error) {
    console.error(error);
    return res.status(500)
      .json({
        message: 'Internal server error', 
      });
  }
  next(error);
};

Yet, this approach won't work for async routes, as they don't directly throw.

For instance, consider the following scenario:

app.get('/malfunction', async (req, res) => {
  throw new Error('Malfunctioning!');
});

To address this issue, you may create a wrapper like so:

const asyncRoute = f => (req, res, next) => {
  return Promise.resolve(f(req, res, next)).catch(next);
};

app.get('/malfunction', asyncRoute(async (req, res) => {
  throw new Error('Malfunctioning!');
}));

But it can become cumbersome as you now have to use this function for each route!

Is there a more efficient way to handle this situation?


  • The solution provided in this Stack Overflow post aligns with the method I described above.
  • On the other hand, the answer found in this Stack Overflow thread does not utilize await.

Answer №1

Essentially, it is not advisable to directly pass an async function into Express's app.get method because the promise returned by the function won't be handled properly. Therefore, you will have to wrap those async handlers like you are already doing.

To avoid having to do this every time, you can create a utility method at the beginning of your module:

const appGet = handler => app.get(asyncRoute(handler));

Then, instead of using app.get, you can use the new method like this:

appGet('/broken', async (req, res) => {
  throw new Error('Broken!');
});

In the future, you may want to consider exploring Koa as an alternative option.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering difficulties while loading JSON data from a static file?

Utilizing the D3 API, I am able to showcase link analysis where various data points are interconnected. Initially, I managed to display these relationships by hardcoding them within the JSP file alongside the API implementation. However, the challenge ar ...

Interpret the JSON reply

Could someone please explain why my function B() is not responding? <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/ja ...

Shuffling an array and returning it using Javascript/Angular

I have been working on implementing a shuffle/unshuffle feature in my Angular application. The concept is simple - there's a single button that, when clicked, will either shuffle an array and return the shuffled order, or if the array has already been ...

Using Typescript to add an element to a specific index in an array

Currently, I am engaged in a project using Angular2 and Firebase. My goal is to consolidate all query results under a single key called this.guestPush. Within my project, there is a multiple select element with different user levels - specifically 4, 6, ...

InternJS - Unresolved TypeError: The undefined object does not have a property named 'readFile'

I am currently facing an issue with Intern.js during functional testing. The error mentioned in the title has me puzzled as I struggle to figure out how to successfully load json files through FS or require. Despite my best efforts and extensive searches o ...

"Learn how to efficiently incorporate data into data-binding in VUE JS with just a

In my data binding, there is a string that reads as follows: bc-men,bc-men-fashion,bc-men-underwear I want to create an input field where I can enter "bc-some-category", click "Add", and have it appended to the end of the list with a comma in front. Her ...

Navigating the contents of the text file using TypeScript

After locating the file flight.txt, I have obtained the following flight information: 1 DFW BOM 2016-05-20 12:20 2016-05-21 02:40 1084.00 JetAirways 100 2 DFW DEL 2016-04-24 17:15 2016-04-25 07:20 1234.00 Lufthansa 100 3 DFW FRA 2016-06-05 13:30 2016-06-0 ...

Managing the rendering of a functional component using React/Redux

I have encountered an issue with my app where it updates too frequently. Within my reducer, there is a specific action called checkTasks. This action essentially scans through the list of current tasks and moves any expired tasks from the main tasks array ...

Guide to acquiring the webViewLink using Google Drive Api v3?

I'm having trouble locating the webViewLink. The documentation (https://developers.google.com/drive/api/v3/reference/files) states that I should receive this parameter when requesting gapi.client.drive.files.list(). However, I don't even have a c ...

When using Node.js with Express and ssh2, my data structures remain intact without any resets when loading web pages

To display jobs sent by users to a cluster, the code below is used (simplified): var split = require('split'); var Client = require('ssh2').Client; var conn = new Client(); var globalRes; var table = [["Head_1","Head_2"]]; module.exp ...

Displaying a selection of file options in a dropdown menu with clickable links to each

I'm looking to create a dropdown menu that displays all PDF files I have in a specific directory, with each file listed being clickable and able to link to its corresponding PDF file. I've attempted various approaches and managed to successfully ...

Load specific options only when needed while maintaining the previously selected state

First off, check out this demo to see what I mean. I have a basic form with a dropdown field. Initially, only one option is pre-loaded and selected. The goal is to load the remaining options when the dropdown is clicked. This functionality works fine, exc ...

Plotting data with both line and nested plot in d3

My plot graph has the correct color scheme, but I need to connect each plot with lines. There are two groups of plots that need to be nested into separate line groups. I'm unsure how to proceed with this task. <!DOCTYPE html> <html> < ...

Create a dynamic 3D model of the human body using JavaScript, AngularJS, or Three.js with

Looking to develop an interactive 3D human model that allows users to input data by clicking on various body parts. Interested in exploring capabilities using JavaScript, AngularJS or Three.js. ...

Moving a page from one location to another in HTML following validation steps

Below is the code snippet I have been working on: index.html <html> <head></head> <body> <div id="top"> New Record </div><br> <form name="myForm" onsubmit="return validateForm()" method="post"> <h5&g ...

Is there a way to have these slides repeat automatically?

After spend some time working on this, I've hit a roadblock. I managed to create a div slider with navigation arrows where each slide has a minimum width of 80px. The code functions correctly, except that when I reach the last item and try to naviga ...

Guide for displaying information as a grid or table format using Angular 4

I am tasked with handling data from an external microservice that is not always in a standard format. The data is dynamic and can include table data, along with metadata information above the grid. My challenge is to render or identify the table data, disp ...

Are there any security measures integrated into ExpressJS?

In my quest for information, I scoured the documentation but unfortunately found no details on the security measures offered by ExpressJS. As I am more familiar with Node's HTTP module, I presume that is what I will be comparing it to ...

Customize the appearance of the v-autocomplete component in Vuetify

How can I style the autocomplete component to only show words that begin with the letters I'm typing, rather than all words containing those letters? Also, is there a way to display the typed letters in bold without highlighting them? https://i.sstat ...

What is the solution for the error message "preventing setting headers after they have been sent to the client" in Node.js?

Even though this question has been posed numerous times before, the solutions provided haven't quite resolved my issue. I've set up a protected route to locate a user. This request is validated through an authenticate middleware that verifies th ...