Reputation: 163
Lately I'm going through the implementation of Global Error Handling Middleware in node.js. Then, I came across this Error.captureStackTrace(this,this.constructor).
I have checked the Node documentation & found that - Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.
MDN Docs - Maintains proper stack trace for where our error was thrown
appError.js File
class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
// Error.captureStackTrace(this, this.constructor);
}}
app.js File
const AppError = require('./appError');
const express = require('express');
const app = express();
app.all('*', (req,res,next) => {
const custErr = new AppError('Mentioned Route is not available on server','404');
next();
})
My Observations when I tried to debug the code:
Can someone explain me on this?
Upvotes: 13
Views: 54007
Reputation: 283
In my case, I had set the wrong path, so the node did not find the right path and what I did was:
Upvotes: -1
Reputation: 560
So Today I got this error so what you have to do is follow these steps.
first of all, kill your ports by using npx kill-port 8000 see this
Upvotes: -1
Reputation: 43
You can add this to your package.json file.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --experimental-modules --es-module-specifier-resolution=node index.js"
},
Upvotes: -1
Reputation: 24565
One thing you need to understand is that apart from instances of the Error
-classs the throw
-statement can also throw other types. Consider this for example:
function throwSomeObj() {
throw {statusCode: 500};
}
try {
throwSomeObj();
} catch(err) {
console.log(err);
console.log(err.stack);
}
The exception that is thrown yields the object you passed to it, i.e. {statusCode: 500}
. Now, as you can see this object does not have any stack-trace, since undefined
is logged.
However, you can use Error.captureStackTrace
to capture the stack-trace where you throw the error. Consider this:
function throwObjWithStacktrace() {
const someError = {statusCode: 500}
Error.captureStackTrace(someError)
throw someError;
}
try {
throwObjWithStacktrace();
} catch (err) {
console.log(err);
console.log(err.stack);
}
As you can see, now err
contains the stack property and contains the stack to the function where the error was thrown.
Note that when instantiating a new Error
-object the stack will automatically be set on that object.
Upvotes: 9