Adding caller information to error stack trace in a Node.js application

I have a function named inner that executes a series of asynchronous operations:

function inner(input) {
    return step1(input)
    .then(step2)
    .then(step3)
    .catch((e) => {
        throw e
    })
}

I propagate the error from inner so I can manage it at the caller level.

Take a look at this simple example:

app.get('/', function(req, res){
    inner(req)
    .then(result => {
        res.render('foo', result)
    }).catch((e) => {
        res.render('error', e);

        //eventually this would be changed to logger.error(e)
        console.log(e);
    })
})

The issue is that when logging the error, only the stack trace displays the inner function but not the calling file. If I were to use this function multiple times in my code and an error occurs, I would need to identify which section of my code invoked it.

Is there a way to include caller information in the error stack trace?

Answer №1

Unique Attribute

Error.prototype.stack is labeled as a non-standard feature, meaning that different platforms may interpret and display it differently.

I decided to test this in Chrome using the following files:

index.html

<!doctype html>
<html>
  <head>
    <script src="inner.js"></script>
    <script src="caller1.js"></script>
    <script src="caller2.js"></script>
  </head>
  <body></body>
</html>

inner.js

function inner() {
  return new Promise((resolve, reject) => {
    reject(new Error('Oh no'))
  }).catch(e => { throw e })
}

caller1.js and caller2.js

inner().catch(e => { console.log(e.stack) })

The output in the console was:

Error: Oh no
    at Promise (setup.js:3)
    at Promise (<anonymous>)
    at inner (setup.js:2)
    at caller1.js:1
Error: Oh no
    at Promise (setup.js:3)
    at Promise (<anonymous>)
    at inner (setup.js:2)
    at caller2.js:1

Both the inner() function and its callers are included in the stack trace.

Solution

If you are encountering issues with this feature, consider manually logging it in the catch() of the caller.

For browser executions, utilize document.currentScript along with its src property to determine the filename.

Update: Node.js Environment

Testing this in Node.js v8.1.2 revealed that both inner() and its callers were also displayed in the stack trace.

An interesting point from the Node.js documentation caught my attention:

Frames are only created for JavaScript functions. If execution passes through a C++ addon function like cheetahify, which then calls a JavaScript function, the frame representing the initial call to cheetahify will not appear in the stack trace.

This inconsistency could explain varying results experienced.

Ultimately, manual logging of filenames may still be necessary, depending on how the files are imported and executed originally.

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

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

Ways to transform the DropBox chooser button into an image

I'm looking to incorporate an image in place of Dropbox's default chooser button. Despite reviewing their API documentation, I haven't come across any methods to use alternative elements for the Dropbox chooser. Does anyone have a solution f ...

The inline $Emit function is not generating the correct random number when using Math.random()

I've been diving into the concept of $emit event in Vue and came across this tutorial: . I tried implementing something similar using Vue2.js, but every time I click the button, it gives me a rounded number instead of a random number like in the guide ...

Using Three.js to rotate a camera-followed sphere in the scene

Currently, I'm developing a Three.js scene with a toy concept where I aim to track a sphere using a camera [demo]. However, I am facing an issue wherein I can't seem to get the sphere to "roll" without causing the camera to also rotate along with ...

Add small pieces of content to CKEditor

Is there a way to add "atomic" block content into CKEditor? For instance, I would like to add <h1>Test</h1> right after the letter "B" in the sentence <p>A B C</p>. Currently, when using CKEDITOR.currentInstance.insertHtml('&l ...

Exploring the implementation of useMediaQuery within a class component

Utilizing functions as components allows you to harness the power of the useMediaQuery hook from material-ui. However, there seems to be a lack of clear guidance on how to incorporate this hook within a class-based component. After conducting some researc ...

Issues with Ajax calls not functioning properly within CakePHP

I'm attempting to make an AJAX request in CakePHP. The submit button is marked as #enviar and the action as pages/contato. This is the code for my AJAX request: $(document).ready(function() { $('#enviar').click(function(){ $. ...

Exploring Angular 4.0: How to Loop through Numerous Input Fields

I am looking to loop through several input fields that are defined in two different ways: <input placeholder="Name" name="name" value="x.y"> <input placeholder="Description" name="description" value"x.z"> <!-- And more fields --> or lik ...

Having trouble with jQuery's scrollLeft function on elements that are not currently visible

Within a large container DIV that contains numerous other elements and has a scroll bar, an issue arises when determining the value of scrollLeft. When the DIV is visible, the scrollLeft() function returns the correct value, but when the element is hidden, ...

Running a setTimeout function within the context of a jQuery each

My goal is to animate characters one by one, but for some reason the following code isn't functioning as expected: $('.overlay-listing').hover(function(){ var idx = 1; $('.strip-hov span', this).each(function(){ if ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

The presentation of the Google graph with dynamically changing data appears to be displaying inaccurately

I am looking to incorporate a graph displaying sales and purchase data on my webpage. Users should be able to select from categories like Purchase, Sales, or Production. I have separate tables for Purchase (AccPurchase) and Sales (AccSales), with productio ...

How to stop a component template in Angular from displaying both conditional statements simultaneously?

I want to prevent my component template from briefly displaying both conditional statements when the condition changes after the component has been initialized. My application receives a token, and depending on its validity, it shows the appropriate conte ...

BS4 Dynamic Countdown Clock

I have successfully integrated a countdown timer into my website, utilizing the following HTML code: <div id="clockdiv"> <div> <span class="days"></span> <div class="smalltext">Days</ ...

Embedding HTML Tags within an array element

The task at hand involves adding an HTML element from Array Value to the Document Object Model template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: &a ...

Tips for creating a div that gracefully fades out its background image when hovered over, while keeping the internal content unaffected

I am looking to create a hover effect on a div element that has a background-color, background-image, and text. What I want is for the background-image to slowly disappear when the div is hovered over, while keeping the text and background color visible. I ...

Accessing elements in AngularJS through ng-click function

According to information provided in this answer, it is necessary to pass the $event object to the ng-click function in order to access the target element. $scope.setMaster = function(obj, $event){ console.log($event.target); } Although using event.t ...

Automating the deployment of a vue.js app using GitLab CI/CD pipeline to deploy to

Currently experiencing an issue with the pipelines involving my YAML file that automates deployment of a Vue app to Firebase. Despite including scripts in the file and setting up the Environment variable FIREBASE_TOKEN on GitLab, pushing the code to a GitL ...

The web method within the aspx page is failing to execute

On page load, I am attempting to make an ajax request using the AngularJS $http service to fetch JSON data from a web method located in my User.aspx.cs page. The web method is defined as follows: [WebMethod] [ScriptMethod(ResponseFormat=ResponseForma ...

unable to employ angular ui-sortable

I got the most recent source code from https://github.com/angular-ui/ui-sortable. However, I am facing issues in using it. The demo.html file seems to be broken. Update: Upon inspecting the console when opening demo.html: Navigated to https://www.google. ...