What is the best way to enhance an error object in Express with additional information beyond just a simple message?

I need to enhance the error handling process in my express application by passing two pieces of information to the error handler, which will then send both pieces of information in a JSON format to the client. Currently, I am only able to include an error message like this:

    app.use((req, res, next) => {
      var err = new Error('test error 1');
       err.status = 404;
    next(err);
     });

However, I want to not only provide the error message but also specify the position where the error occurred so that the client can display the message accurately. Something along these lines:

    app.use((req, res, next) => {
      var err = new Error({err: {pos: 'field3', msg: 'test error 1'}});
       err.status = 404;
    next(err);
     });

After setting up the error object with multiple properties, I plan to send this information to the client using the following code:

 app.use((err, req, res, next) => {
    res.status(err.status || 500);
    res.json(err.message);
 });

The issue is that creating the error object only allows for a single string value for the message. How can I effectively pass multiple pieces of information (potentially comprising more than just two parts) through my error handling middleware?

Answer №1

If you need to handle a page not found error, you can try this approach:

app.use((req, res, next) => {
  res.status(404).json({
     message: 'Page Not Found',
     errorMessage: 'error'
  });
}

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

jQuery Mobile is experiencing page height inaccuracies

My web application, built with jQuery Mobile 1.2.0, is encountering an issue with page height calculations on Windows Phone. While iOS and Android display correctly, there is a gap at the bottom of the page on Windows Phone. Is there a CSS-only solution t ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

Adjust the size of an iFrame's content according to the dimensions of the iFrame

I am looking to use an iFrame for embedding a map, and my goal is to resize the map according to the values in the iFrame tag. Most tutorials I have found focus on auto-sizing the iFrame based on content, which is not what I need. Just to make it clear, I ...

The lack of definition for e.PreventDefault causes an error

In my code, I have a registerAjax(e) function: function registerAjax(e) { e.preventDefault(); let userData = { username: $("#username").val(), password: $("#password").val(), }; $.ajax({ method: "POST", url: kinveyBaseUrl + "user/" + kinve ...

Could there be a mistake in the way array combinatorics are implemented in JavaScript?

Having encountered the necessity for generating unique combinations when dealing with multiple arrays, I developed this script. While it functions as intended during the combination process, storing the result in a final array yields unexpected outcomes. ...

Raspberry Pi Fast Server: Issue with AJAX not locating images in directory and malfunctioning ID search

I'm completely new to Raspberry Pi, linux, and server concepts, so I'd appreciate explanations at a beginner level. My goal is to create a display similar to those you see in lobbies showing corporate slides and weather updates. While setting up ...

Guide on transforming Div content to json format with the use of jquery

I am trying to figure out how to call the div id "con" when the export button is clicked in my HTML code. I want it to display JSON data in the console. If anyone has any suggestions or solutions, please help! <html> <div id ="con"> < ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...

Tips for displaying an HTML page using JavaScript

In my project, I am working with an .html file (File X) that needs to immediately open another .html file (File Y) based on a certain value. Could someone provide guidance on the best way to achieve this using JavaScript? Additionally, I would like the pa ...

Enhancing XTemplate in ExtJS 4.2.1 with dynamic data refresh from store

Here's a situation that's quite unique... A DataView linked to a store is causing me some trouble. In the XTemplate, I want to display the quantity of a specific type of JSON record. Each record has a 'type' property with a value. For ...

Developing applications using ReactJS with Typescript can sometimes lead to errors, such as the "onclick does not exist on type x

In the code snippet below, I have a method that renders a delete icon and is used in my main container. Everything functions correctly except for a small cosmetic issue related to the type any that I am struggling to identify. import React from 'reac ...

Issue encountered when attempting to utilize filters with strapi V4 graphql and nextjs, functionality not working

Currently, I am using strapi V4 along with the graphql extension. Everything works fine when I use filters with variables in the graphql Playground. query getOrdersFilterList($searchstring: String!) { orders(filters: { customer: { contains: $searchstring } ...

standards for matching patterns (such as .gitignore)

Throughout my experience, I have utilized various tools designed to search a codebase for specific files and then carry out operations on those files. One example is test libraries that identify all the necessary files for execution. Another common tool is ...

What is the best time to inquire about the client's currency preference in the absence of a country code in the `accept-language`

Explaining the Functionality: Identifying Client Currency To determine the client's preferred currency, I extract their locale information from the accept-language header. By analyzing the language and country codes within the accept-language header, ...

Incorporating an HTTP header into d3.json using queue.js

I know that I can include a header in a D3 JSON request by using the following code: d3.json("http://localhost:8080/data") .header("Application-ID", "1") However, I'm uncertain about how to add this header when utilizing queue's defer method. ...

What is the process for transforming binary code into a downloadable file format?

Upon receiving a binary response from the backend containing the filename and its corresponding download type, the following code snippet illustrates the data: 01 00 00 00 78 02 00 00 6c 02 00 00 91 16 a2 3d ....x...l....... 9d e3 a6 4d 8a 4b b4 38 77 bc b ...

Attempting to showcase the information in my customized SharePoint Online list through a Web Part Page utilizing AngularJS

<script> //AngularJS Code goes here var appVar = angular.module('listApp', ['ngRoute']); appVar.controller("controller1", function($scope){}); function FetchEmployeeData($scope, EmployeeList){ var reque ...

Working with variables passed from Node.js in Jade processing

Currently, I have a situation where my script is sending a matrix that looks like this: [[1,2,3,4], [7,6,5,4], [2,3,4,5]]. After sending it using res.send(JSON.stringify(dataArray)); and viewing it in jade with h1#results, I can see that the format appears ...

Firebug detected an error with the regular expression flag "h" after executing the YUI Compressor

When I run YUI Compressor, an error occurs with the message: invalid regular expression flag h [Break On This Error] ction(event){$(this).removeClass('lumi...cs_glb.php</b> on line <b>221</b><br/> The issue seems to be with t ...