Throw await syntax in Nodejs async express handler is not working


const express = require("express");
const expressAsyncHandler = require("express-async-handler");

const app = express();

const f = async () => {
  return false;

  expressAsyncHandler(async () => {
    throw await f();
  () => {
    console.log("the bug!");

app.use((err, req, res, next) => {
  console.log("caught!", err);

app.listen(4000, () => console.log("listening on port 4000..."));

Expected output on the console:



the bug!.

question: Why? Is it a bug in async-express-handler package or is it a normal JavaScript behaviour? what if I want to throw await something inside? how ?


Your problem is that you’re throwing the value false. This doesn’t fit into nodejs’ callback conventions (and by extension, express error handling), which requires the err parameter to get a truthy value to be considered an error. A much simpler way to reproduce the issue:

  (req, res, next) => {
    // or even just:
  () => {
    console.log("the bug!");

So just don’t do that! Always throw an Error, not a string, not something else, and this principle also holds for promise rejections.

Answered By – Bergi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published