Errors slipping through the cracks of Express middleware

When it comes to using express and typescript, I am attempting to create a middleware for error handling similar to Sentry. Below is the code snippet:

 const catchError = (
  error: Error,
  req: Request,
  _res: Response,
  next: any
) => {
   console.log("ERROR: ", error);
   //some logic

  next(error);
}

In my index.ts file:

  app.use(bodyParser.json({ limit }));
  app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));

  app.use(express.json());
  app.use(cors({ credentials: true, origin: true }));

  app.use(bodyParser.urlencoded({ extended: false }));
//controllers

app.use(catchError as express.ErrorRequestHandler)

I'm wondering why my middleware only works when I include this:

} catch (error) { 
   next(error);
}

inside the function where the error occurs, and it does not work without it. Can this middleware handle errors and exceptions without using next(error)?

Any help would be greatly appreciated!

Answer №1

To implement that custom error handler, consider adding a method override in your code.


const methodOverride = require('method-override')

app.use(bodyParser.json({ limit }));
app.use(morgan("[:date[iso]] :method :url :status :response-time ms"));

app.use(express.json());
app.use(cors({ credentials: true, origin: true }));

app.use(bodyParser.urlencoded({ extended: false }));

// Enhance the functionality with this method override
app.use(methodOverride())

app.use(catchError as express.ErrorRequestHandler)

For more information, check out:

https://expressjs.com/en/guide/error-handling.html

https://www.npmjs.com/package/method-override

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

Utilize JavaScript or JQuery to create a dynamic pop-up window that appears seamlessly on the

Looking to create a unique feature on an HTML page? Want a clickable link that opens a "pop-up" displaying a specific image, right within the page rather than in a new tab or window? Ideally, this pop-up should be movable around the page like a separate ...

What is the method to define a loosely typed object literal in a TypeScript declaration?

We are currently in the process of creating TypeScript definitions for a library called args-js, which is designed to parse query strings and provide the results in an object literal format. For example: ?name=miriam&age=26 This input will produce th ...

How can you use JavaScript to create a JSON object using values from an HTML form textarea and then send

I need to create an HTML form that will send specific information in the Http-request body. { “info” : { “id” : “123” “text1” : <data from html text-box> } Therefore, my goal is to convert the provided data into a JavaScri ...

Assign values from an array in jQuery to a <span> element

I am working with the following HTML code: <input type='radio' class='at-radio' name='re_widget[0][set_style_for_widget]' value='topbanner' /> <span class='at-radio-label'>topbanner</span> ...

Uncover the hidden message in a string encoded for JavaScript

This encoded HTML code is intended for use in a JavaScript function <div class=\"ProductDetail\"><div style=\"width:780px\">\r\n\t<div class=\"baslik\" style=\"margin: 0px; padding: 5px 10px ...

Refreshing the v-model in a child component

Within my parent component, the code structure is similar to this: <template> <ProductCounter v-model="formData.productCount" label="product count" /> </template> <script setup> const initialFormData = { ...

Arrange JSON response data in alphabetical order

Looking to sharpen my skills by working with public APIs in JavaScript. My goal is to sort the list of items alphabetically by the h4 value (food name) when the query is submitted. I attempted to use .sort() on the response item before using .map(), but en ...

Unable to achieve the desired focus on a specific element using JavaScript's .focus() method

After executing the command $('#someelement').focus(), I am not receiving any error message but the functionality is not working as expected. Even when I attempt to retrieve document.activeElement, it continues to return the body element. Here i ...

Bind the prototype to the JavaScript object

Consider this scenario where I have JSON data containing person objects. [ { "name": "Alice", "age": 28, }, { "name": "Bob", "age": 33 } ] Upon parsing, an array with two JavaScript objects is obtained. Suppose I want to add a ...

Component that can be used multiple times to load data

I am currently working on a react/nextjs/redux application where each component needs to call a different backend API. The main challenge I am facing is the lack of reusability in loading data components due to some repetitive code that I would like to el ...

Send Ajax request following input verification

My knowledge of JavaScript is limited, but I was able to create a form that uses AJAX by copying and pasting some code. I have also implemented standard Bootstrap 5 input validation for the form. Everything was working fine until I realized that the AJAX ...

Key constraints in generics: a key must belong to a distinct object type

Is there a way to enhance the safety of this function even further? Consider this object/shape: export const initialState: State = { foods: { filter: '', someForm: { name: '', age: 2, ...

How to attach an event listener to an input element using Angular

I am looking to add a listener to an input element that will be triggered every time the user changes the input values. The goal is to display the current values chosen by the user. Example HTML template: <div id="idDoseLabel1" class="da ...

Implement a personalized auto-fill feature in Angular triggered by a user's

I am looking to implement a customized autocomplete feature on an input element in Angular 8. Currently, I have the following setup to capture the tab key press: <input (keydown.Tab)="onKey($event)" /> Then, in my .ts file, I have the following me ...

Is there a way to differentiate the color of an active link from an inactive one, so users can easily identify which link they are currently viewing?

How can I customize the color of text for the active page on my website's sidebar? For example, I have two hyperlinks, one for HOME and one for ABOUT. When a user clicks on the HOME link, I want the text color to change to green while the ABOUT link r ...

PhantomJS reveals underlying jQuery bug

Currently, I am developing automated test scripts that require a headless browser (PhantomJS) to perform all DOM navigation and actions except for downloads. So, PhantomJS seems like the right choice. However, I am encountering errors when trying to use P ...

Maximizing the efficiency of threejs through combining and selecting items

In my exploration of three.js optimization, I discovered that reducing the number of draw calls is crucial for improving performance. One way to achieve this is by consolidating geometries through the use of GeometryUtils.merge. Although this optimization ...

Using the Handlebars view engine in Node.js to write Angular code on Hapi.js

After creating an API in Hapi, I decided to include a view file within the folder structure of Hapi.js to render an HTML file. Using the Handlebars engine and Vision support library on Hapi.js, I was able to display the HTML file successfully. However, whi ...

Simple Express Path Challenge

I've hit a roadblock in my JavaScript tutorial on Mozilla and could really use some assistance. Below are excerpts from 3 different files: a) In the app.js file, I am trying to locate Router handlers and then present them: //app.js //the fol ...

Incorporating telepat-io into a Java Struts enterprise solution

Our J2EE enterprise application, built on Java Struts, has a static front end. Our team's architect has opted to enhance the user authentication by incorporating Ajax and JavaScript functionalities using telepat-io. The project is currently managed w ...