Managing unanticipated errors in Express while utilizing async/await mechanics

Consider this TypeScript code snippet:

app.get('/test_feature', function (req: Request, res: Response) {
    throw new Error("This is the bug");
});

app.use(logErrors);

function logErrors (err: Error, req: Request, res: Response, next: NextFunction) {
    console.log(err);
    mongoDal.log(err.message, err);
    next(err);
}

In the above code, when an error is thrown in a request handler, it triggers the logErrors function as expected.

However, if we modify the code to include an async function:

app.get('/test_feature', async function (req: Request, res: Response) {
    throw new Error("This is the bug");
    await someAsyncFunction();
});

Since the function is now asynchronous, the error is caught by Express's default error handler, bypassing both the custom error handler and Node's default error handler:

process.on('uncaughtException', function (err: Error) {
    try {
        console.log(err);
        mongoDal.log(err.message, err);
    } catch (err) {

    }
});

How can we ensure that the 'logErrors' function is called when an error occurs within an async function? Is there a generic solution without having to wrap every async function in a try/catch block?

Answer №1

The issue at hand is that your handler no longer throws a synchronous exception. Instead, it returns a promise that gets rejected. This problem extends beyond promises and async/await usage - it's a common pitfall in any express code utilizing callbacks as well. If error handling is not carefully implemented in all parts of async code, errors can easily slip through the cracks.

To address this specific case, something must be in place to catch rejections from the promise being returned. Here are a few approaches:

  1. Add a .catch() method to all error handlers to manage errors manually or delegate them to the standard express error handling by calling next(err).
  2. Create a wrapper function for your handler to handle this task consistently throughout your codebase. Utilizing an existing function like express-promise-wrap can simplify this process.
  3. Enhance the functionality of .get and similar methods to automatically monitor rejections in promises returned by handlers. While manual implementation is possible, tools like express-as-promised offer a ready-made solution (though personal testing is recommended).

Option 3 may require more initial setup, but once configured, it's the most efficient choice in my view. With this approach, you can use async functions directly as handlers, knowing that they'll return promises internally while automatic monitoring ensures any subsequent failures are caught.

For further insight on this topic, StrongLoop has an article diving deeper into async error handling in expressJS:

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

Stop observing IntersectionObserver within the React.useEffect function

I'm attempting to retrieve the top and bottom measurements from multiple elements using the IntersectionObserver. However, once I have the measurements, I'm unsure how to stop observing the elements. The issue is that each element has a position ...

Unable to view form data in .php file

How can I change the style of my "Submit" button when a user clicks on it to submit the form? The action attribute calls a PHP file, but the data doesn't show up until I remove the onSubmit attribute from the form. However, without it, I cannot use t ...

Connect CSS Transition to a click action

Below is the code snippet. When you click on the div, it creates a folding effect to the left. You can view it here. I want to link this effect to the arrows I use for sliding back and forth. For example: The left arrow should move the slide to the l ...

HTML code featuring multiple dropdown menus, each equipped with its own toggleable textarea

I have multiple HTML drop downs, each triggering a textarea based on the selection. Currently, I'm using show and hide JavaScript functions for each question individually. Is there a way to streamline this so that I don't have to write separate c ...

The utilization of TypeScript featuring a variable that goes by two different names

As I dive into TypeScript code, coming from a Java background, I struggle to grasp the syntax used in this particular example. The snippet of code in question is extracted from the initial Material UI Select sample: const [labelWidth, setLabelWidth] = Rea ...

retrieving the outcome from a PHP script invoked through Ajax

Having trouble transferring the results of a PHP script to HTML input fields This is my PHP script: $stmt->execute(); if ($stmt->rowCount() > 0){ $row = $stmt->fetch(PDO::FETCH_ASSOC); echo 'Located: ' . $row[&ap ...

What role does @next/react-dev-overlay serve in development processes?

Currently, I am diving into a NextJs project. Within the next.config.js file, there is this code snippet: const withTM = require('next-transpile-modules')([ 'some package', 'some package', 'emittery', ...

Set up webpack on your Mac using npm

Seeking help to install webpack using npm: sudo npm install -g webpack The following error message is encountered: node-pre-gyp WARN Using needle for node-pre-gyp https download node-pre-gyp WARN Pre-built binaries not installable for <a href="/cdn- ...

Incorporate an Ajax response script with a Django HttpResponse

How can I pass the ajax response obtained from the view to the template using HttpResponse? I'm unsure of the process. view.py analyzer = SentimentIntensityAnalyzer() def index(request): return render(request, "gui/index.html") @csrf_exempt d ...

Troubleshooting Issues with Passing Values in jQuery AJAX POST Requests

Currently, I am working on two basic PHP pages: notification.php <html> <head><title></title> <meta charset="UTF-8"> <script src="https://cdn.firebase.com/js/client/2.4.2/firebase.js"></script> <script src="ht ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...

Using Javascript within AEM to update a class upon checkbox selection

I need assistance targeting the 'horizontal-video' class within a div in an AEM component. I am attempting to add a second class called 'flipped' to the div if the author clicks on a checkbox with the ID of 'coral-id-540'. Unf ...

The Evolution of Alternatives to contentEditable

Related: ContentEditable Alternative I am curious about the timeline of online WYSIWYG editors prior to the existence of contentEditable. I remember using GDocs and GMail with rich-text features that functioned similarly to contentEditable. I would appre ...

Error message in Angular 2: Unable to locate node module for import

Recently, I encountered an issue while attempting to utilize a specific node module called aws-api-gateway-client Although the installation was successful, I am facing difficulties with importing this module due to an error. Oddly enough, it works seamle ...

Embed a website in an iframe and modify a portion of the URL within the embedded page

Welcome to my first question here! I am looking for a solution that will allow me to load a webpage inside an iframe while modifying parts of the URLs in any links on the page with different text. For example, let's say we load a website like "myweb ...

Fetching data from an Angular Universal server API

Recently, I updated my application to Angular 6 + Universal and it has been a positive experience overall. However, there are two specific issues that I am currently facing. I would greatly appreciate assistance in resolving both problems: 1- Is there a w ...

Can you explain the process of obtaining getServerSideProps results for my IndexPage?

Having trouble with the getServerSideProps function. I'm a beginner and struggling to figure out why it's not running properly. Spent hours trying to fix it, but still getting undefined in the IndexPage console.log(props.data) export default fun ...

Backend data not displaying on HTML page

I am currently working on an Angular 8 application where I have a service dedicated to fetching courses from an API endpoint. The service method that I'm using looks like this: loadCourseById(courseId: number) { return this.http.get<Cours ...

What makes TypeScript code run successfully using `node` instead of `ts-node` by mistake?

I have created a basic node.js project using TypeScript. Here is the content of my package.json file, which lists all the packages I have installed (without including ts-node): { "name": "mydemo", "version": "1.0.0", "description": "", "main": "ind ...

When sorting in AngularJS using the orderBy filter, remember that string values should come before numeric values: for example, sort as follows (n/a, 0,

While running an AngularJS filter sorting on a table, I encountered an issue where if the value is 'n/a' (which is a numeric string), the sorting is incorrect. I expected the order to be n/a, 0, 1, 2, 5, 100 since strings should be considered l ...