Express failing to manage errors coming from controllers or other classes

Whenever I make a request and encounter an error, the error middleware is supposed to handle it. For example:

# routes.ts
// sending an error
router.get('/', (req, res) => {
    throw new BadRequestError("test")
})

This triggers the errorMiddleware and processes the error successfully. However, when I trigger an error from the controller, like so:

# UserController.ts
export class UserController {
    static async registerNewUser(req: Request, res: Response) {
        const newUser = new User(req.body)

        const alreadyExists = await User.findUser(newUser)

        if (alreadyExists) {
            throw new BadRequestError("test")
        }
    }
}

And then route it accordingly:

# routes.ts
router.post('/register', UserController.registerNewUser)

The middleware doesn't get called and the application crashes. Here's a snippet of my app.ts code:

# app.ts
const app = express()

app.use(express.json());

app.use(router)

app.use(errorMiddleware)

export { app }

This is what my server.ts code looks like:

# server.ts
import { app } from "./app";

const PORT = process.env.PORT

app.listen (PORT, () => console.log(`Server is running on port ${PORT}`))

I've experimented with changing the error middleware and adding additional ones, but nothing seems to work. I also attempted to remove errors from subclasses and pass them directly to controllers, but faced the same issue.

I hope to be able to send and manage errors from any class within my API using the designated middleware.

Answer №1

Be sure to set up the express-async-error package.

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

The functionality to refresh an input field upon clicking a button is not functioning as expected

I am currently developing a small MVC.NET web application with user input functionality. The goal is to calculate and display the results in two input fields upon button click. However, I am facing an issue where the input fields remain empty after the but ...

What steps should I take to choose esNext from the typescript menu within visual studio 2017?

When utilizing dynamic import with TypeScript in Visual Studio 2017, I encountered the following error: TS1323(TS) Dynamic imports are only supported when the '--module' flag is set to 'commonjs' or 'esNext'. I attempted to c ...

Creating test cases in Dalek.js using functions

I've recently started using Dalek.js for testing and have found it to be quite beneficial. I am interested in taking some tests from one of my files and transferring them into a separate file named "common_tests.js" so that I can reuse them in other l ...

Having trouble making the jQuery "simulate width: calc(100%)" function work properly?

I am utilizing a combination of HTML, CSS, mediaQuery, Javascript, jQuery, and PrimeFaces in my project. One particular css property I want to use is: calc(100% - 100px) To handle old browsers that do not support this property, I have implemented a javas ...

Toggle the visibility of a text box based on a selected option from a dropdown menu within a dynamic form using Angular

In the form I designed, users have the ability to add one or more divs of Address when they click on the add button. If a user selects options=5 from the dropdown menu, I want to dynamically show and hide a textbox within that specific Address Div. Compo ...

Animating a div in CSS3 to expand horizontally from left to right without affecting its original position

I am currently in the process of developing a calendar using HTML, CSS, and JavaScript. The main purpose of this calendar is to showcase upcoming and past events. However, I am facing difficulties in ensuring that my event blocks occupy the remaining space ...

Issue with displaying the appropriate x-axis label in ReactJS' ApexCharts

I am currently facing an issue with the label display in percentage on a basic ApexChart. The problem lies in correctly displaying the label as a percentage. Below is the code snippet I am using for the x-axis: xaxis: { labels: { formatter: ...

Create Joi Schema based on TypeScript types/interfaces

Searching for a way to convert Typescript types or interfaces into joi schema objects led me to various solutions that did the opposite, such as generating Typescript types/interfaces from joi schemas. I came across options like ts-interface-builder and ts ...

Building a versatile sitemap using MongoDB, Node.js, Express, and EJS: A comprehensive guide

Currently, I am in the process of developing a dynamic sitemap for my website which consists of numerous pages that are frequently updated. The sitemap should be accessible at www.mywebsite.com/sitemap.xml. My approach involves querying the database to re ...

Guide on how to conditionally render Container Classes

Initially, the designer provided me with this: Essentially, a category is passed from the previous screen. Through some UI interactions, I have to render this screen repeatedly. The flow goes like this: you choose a category, if it has subCategories, allo ...

What could be the reason for receiving an array of promises instead of data while fetching information from the blockchain using useEffect?

I've encountered an issue while working with React and fetching data from the blockchain using useEffect. The problem arises when I map the data and store it in the lendingData array - upon logging, it appears as though I'm getting an array of pr ...

There was an issue with vite-plugin-pages stating that it could not locate the module '~pages' or its corresponding type declarations

Currently working on my Vue project, using TypeScript with Vite. To handle routing, I am utilizing the 'vite-plugin-pages' plugin. Encountered a type error while importing routes from the '~pages' directory. Here's a snippet of m ...

Update a median in MongoDB

I am attempting to create a cache of the mean order in order to prevent retrieving all ratings and avoid aggregation (since the mean needs to be frequently obtained): Here is my proposed solution: Product.findOneAndUpdate({_id: id}, {$inc : {rating_count ...

Exploring Screen Navigation in React Native using Typescript

Good day, I am currently working on a react native app project. I am trying to create a simple example to better understand how the navigation works, but I am having trouble replicating the example provided in the documentation. Below is an image showing ...

Ng-Paste - Retrieving Data from Clipboard as a List or Array

The Concept Currently, we are in the process of developing an Angular 1.5.x app and are exploring ways to incorporate a feature that allows users to paste a single column of cells from an excel sheet or another spreadsheet (regardless of row count) into a ...

What is the method to utilize global mixin methods within a TypeScript Vue component?

I am currently developing a Vue application using TypeScript. I have created a mixin (which can be found in global.mixin.js) and registered it using Vue.mixin() (as shown in main.ts). Content of global.mixin.js: import { mathHttp, engHttp } from '@/ ...

What is the proper way to retrieve POST data from a request?

Currently, I am working with Express and Node.js. My task involves extracting POST data from a request to facilitate the Log-in process. Despite my efforts, I have been unable to retrieve the POST data in the request as req.body always returns an empty ob ...

I am looking to create a 2D octagon using Three.js

When attempting to create a regular octagon, I encountered an unusual triangle with this code: var geom = new THREE.Geometry(); geom.vertices.push( new THREE.Vector3(100, 250, 0)); geom.vertices.push( new THREE.Vector3(250, 100, 0)); geo ...

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

How can you leverage both sockets and express middleware at the same time?

Is there a way to access the socket of a request within an express middleware function? For example: import express from 'express'; import io from 'socket.io'; const app = express(); // Integrate app and io somehow ... // When a cl ...