Javascript is losing a backtrace in the catch block - javascript

The following code sample:
async function expectResolutionErrorCode(object) {
try {
await Promise.resolve(1);
object.f1() // caught error
} catch (error) {
object.f2() // uncaught error
}
}
expectResolutionErrorCode(undefined).catch(err => console.log(err));
Produces the following backtrace when run using node v14:
$ node test.ts
TypeError: Cannot read property 'f2' of undefined
at expectResolutionErrorCode (/Users/bogdan/makabu/unstoppable/resolution/test.ts:6:12)
If I comment out the await statement at line 3 from the sample, the backtrace is complete:
TypeError: Cannot read property 'f2' of undefined
at expectResolutionErrorCode (/Users/bogdan/makabu/unstoppable/resolution/test.ts:6:12)
at Object.<anonymous> (/Users/bogdan/makabu/unstoppable/resolution/test.ts:10:1)
at Module._compile (internal/modules/cjs/loader.js:1201:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1221:10)
at Module.load (internal/modules/cjs/loader.js:1050:32)
at Function.Module._load (internal/modules/cjs/loader.js:938:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
So the await statement clearly causes node to lose some part of the backtrace.
Why does it behave like that?
Is there any workaround to maintain the backtrace while still using await statements inside try catch?
I tested this behavior in Chrome and Safari and the stacktrace is lost in almost the same way: https://jsfiddle.net/61kdv8fx/

It's because the stack has unwound. Remember that await is syntactic sugar for hooking the settlement of a promise. So when you reach the await in your code, the function returns. Later, when the code continues because the promise was settled, the stack is shallow because promise reactions are called directly.
JavaScript tool makers are very aware of this and working on async call stacks to address it.
However, I should note that when I try to replicate what you're seeing on Node v14, I don't see it, because V8 already has async call stacks. Example:
async function example() {
try {
await Promise.resolve(1); // Could just be `await 1;`, but I wanted to match the question
throw new Error("boom1");
} catch (e) {
throw new Error("boom2");
}
}
async function a() {
await b();
}
async function b() {
await c()
}
async function c() {
await example();
}
a();
When I run it:
$ node example.js
(node:5342) UnhandledPromiseRejectionWarning: Error: boom2
at example (/path/to/example.js:6:15)
at async c (/path/to/example.js:19:5)
at async b (/path/to/example.js:15:5)
at async a (/path/to/example.js:11:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:5342) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:5342) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I get the same sort of output on modern versions of Chrome and other browsers using a recent V8. But Firefox v78 still loses the context; I'm sure the SpiderMonkey team are working on it.

Related

IPFSAccessController.save ERROR: Error: Deprecated, use .toString()

i'm only trying to launch the exemple of the app kit OrbitDB which is :
import OrbitDB from "orbit-db";
import IPFS from "ipfs";
async function main () {
// Create IPFS instance
const ipfsOptions = { repo : './ipfs', }
const ipfs = await IPFS.create(ipfsOptions)
// Create OrbitDB instance
const orbitdb = await OrbitDB.createInstance(ipfs)
// Create database instance
const db = await orbitdb.keyvalue('ipfs_db')
}
main()
you can find it here : https://github.com/dappkit/aviondb#using-nodejs
but the problem is when i launch it, i got these errors :
Swarm listening on /ip4/127.0.0.1/tcp/4002/p2p/12D3KooWM7D9NdMhtxyiWiKH4XVpuZW5oDu9MbWxFmEzLsG9UynM
Swarm listening on /ip4/192.168.1.53/tcp/4002/p2p/12D3KooWM7D9NdMhtxyiWiKH4XVpuZW5oDu9MbWxFmEzLsG9UynM
Swarm listening on /ip4/127.0.0.1/tcp/4003/ws/p2p/12D3KooWM7D9NdMhtxyiWiKH4XVpuZW5oDu9MbWxFmEzLsG9UynM
IPFSAccessController.save ERROR: Error: Deprecated, use .toString()
at CID.get toBaseEncodedString [as toBaseEncodedString] (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/multiformats/cjs/src/cid.js:94:11)
at Object.writeCbor [as write] (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/aviondb/node_modules/orbit-db-access-controllers/node_modules/orbit-db-io/index.js:62:14)
at async IPFSAccessController.save (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/aviondb/node_modules/orbit-db-access-controllers/src/ipfs-access-controller.js:46:13)
at async Function.create (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/aviondb/node_modules/orbit-db-access-controllers/src/access-controllers.js:68:20)
at async OrbitDB._determineAddress (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/aviondb/node_modules/orbit-db/src/OrbitDB.js:331:37)
(node:8397) UnhandledPromiseRejectionWarning: Error: `undefined` is not supported by the IPLD Data Model and cannot be encoded
at undefinedEncoder (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/#ipld/dag-cbor/cjs/index.js:47:9)
at objectToTokens (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/cborg/cjs/lib/encode.js:175:20)
at Object (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/cborg/cjs/lib/encode.js:149:9)
at objectToTokens (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/cborg/cjs/lib/encode.js:184:10)
at Object (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/cborg/cjs/lib/encode.js:149:9)
at objectToTokens (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/cborg/cjs/lib/encode.js:184:10)
at encodeCustom (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/cborg/cjs/lib/encode.js:214:18)
at Object.encode (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/cborg/cjs/lib/encode.js:236:10)
at Object.encode (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/#ipld/dag-cbor/cjs/index.js:85:41)
at put (/home/zar/Etna4/SmartContract/db_ipfs/node_modules/ipfs-core/src/components/dag/put.js:35:25)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8397) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:8397) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
i seriously don't know what to do, i tried to clear the cache, to delete node_modules and package-lock.json, and do a npm install, but nothing changed, i got the same error, do you have any idea to fix this ?
This error clearly points to an incompatibility between IPFS and OrbitDB.
The latest version of js-ipfs that OrbitDB v0.26.1 supports is 0.55.4.
You should change the ipfs (or ipfs-core) version in your package.json to ^0.55.4.
Note: The upcoming OrbitDB v0.27, will support the latest IPFS version.

How can I solve login error on discord.js [duplicate]

This question already has answers here:
Why am I getting a ReferenceError: AbortController is not defined in Discord.js v13?
(3 answers)
Closed 1 year ago.
const {Client, Intents} = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
client.once('ready', () => {
console.log('Ready!');
});
client.login(token);
I have this code, every time i try to run it returns me the same error:
(node:13284) UnhandledPromiseRejectionWarning: ReferenceError:
AbortController is not defined
at RequestHandler.execute (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:172:15)
at RequestHandler.execute (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:176:19)
at RequestHandler.push (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\rest\RequestHandler.js:50:25)
at async WebSocketManager.connect (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\client\websocket\WebSocketManager.js:128:9)
at async Client.login (C:\Users\Luis\Vainas\Pruebas\node_modules\discord.js\src\client\Client.js:245:7)
(Use node --trace-warnings ... to show where the warning was
created) (node:13284) UnhandledPromiseRejectionWarning:
Unhandled promise rejection. This error originated either by throwing
inside of an async function without a catch block, or by rejecting a
promise which was not handled with .catch(). To terminate the node
process on unhandled promise rejection, use the CLI flag
--unhandled-rejections=strict (see
https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 2) (node:13284) [DEP0018] DeprecationWarning: Unhandled
promise rejections are deprecated. In the future, promise rejections
that are not handled will terminate the Node.js process with a
non-zero exit code.
Dont know how to fix it. I tried and investigate on the documentation but cant find the solution.
I've added this line to my code to find the error:
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection:', error);
});
Getting this:
{ code: 500, method: 'get', path: '/gateway/bot', requestData:
{ json: undefined, files: [] } }
The AbortController package was introduced in Node.js v16 (?). So you need to upgrade your Node.js version. Discord.js v13 requires you to use Node.js v16 and higher as stated in their documentation.
Depending on your operating system, you can either install 64bits or 32bits version of Node.js. Head over to the official website and download 16.8.x (Current, Latest Features) Windows installer.
After installation, verify the version by typing node -v in your console.

Trouble with uploading files to firebase storage

I'm learning about puppeteer and firebase at the moment. What I am trying to do is create a pdf of a web page and upload to firebase storage. This is my code.
const puppeteer = require('puppeteer');
const fs = require('fs').promises;
const firebase = require('firebase');
require("firebase/storage");
const url = process.argv[2];
if (!url) {
throw "Please provide URL as a first argument";
}
var firebaseConfig = {
#Firebase Config Goes here
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
#Function to generate PDF file
async function run () {
const browser = await puppeteer.launch();
const page = await browser.newPage();
//await page.goto(url);
await page.goto(url, {waitUntil: 'domcontentloaded', timeout: 60000} );
//await page.pdf({ path: 'api.pdf', format: 'A4' })
const myPdf = await page.pdf();
await browser.close()
return myPdf;
}
const myOutput = run();
#Upload to Firebase based on the instruction here https://firebase.google.com/docs/storage/web/upload-files
var storageRef = firebase.storage().ref();
// Create a reference to 'mountains.jpg'
storageRef.child(myOutput).put(myOutput)
However, I'm running into this error when executing my code
$ node screenshot.js https://en.wikipedia.org/wiki/Aung_San_Suu_Kyi
C:\Users\ppham\NucampFolder\Test\node_modules\#firebase\storage\dist\index.cjs.js:1040
.split('/')
^
TypeError: childPath.split is not a function
at child (\Test\node_modules\#firebase\storage\dist\index.cjs.js:1040:10)
at getChild (\Test\node_modules\#firebase\storage\dist\index.cjs.js:2610:19)
at ReferenceCompat.child (Test\node_modules\#firebase\storage\dist\index.cjs.js:2833:25)
at Object.<anonymous> (C:\Users\ppham\NucampFolder\Test\screenshot.js:55:12)
at Module._compile (internal/modules/cjs/loader.js:936:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:947:10)
at Module.load (internal/modules/cjs/loader.js:790:32)
at Function.Module._load (internal/modules/cjs/loader.js:703:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:999:10)
at internal/main/run_main_module.js:17:11
It is saying that childPath.split is not a function. I'm pretty confused at this since I've already installed all the firebase packages. I've been searching for this error for a while but no luck so far. Anyone knows how to resolve this issue?
===============================================================================
Edit #1: As Frank pointed out below, I have to change storageRef.child(myOutput).put(myOutput) to something like storageRef.child("filename.pdf").put(myOutput). It runs but I'm running into this error afterwards.
$ node screenshot.js https://google.com
Promise { <pending> }
(node:20636) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'byteLength' of undefined
at C:\Users\ppham\NucampFolder\Test\node_modules\#firebase\storage\dist\index.cjs.js:833:40
at Array.forEach (<anonymous>)
at Function.FbsBlob.getBlob (C:\Users\ppham\NucampFolder\Test\node_modules\#firebase\storage\dist\index.cjs.js:832:25)
at multipartUpload (C:\Users\ppham\NucampFolder\Test\node_modules\#firebase\storage\dist\index.cjs.js:1519:24)
at C:\Users\ppham\NucampFolder\Test\node_modules\#firebase\storage\dist\index.cjs.js:2003:31
at C:\Users\ppham\NucampFolder\Test\node_modules\#firebase\storage\dist\index.cjs.js:1900:21
at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:20636) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20636) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This looks to imply that myOutput doesn't contain anything. I thought that I have return the pdf in the run function and it will be passed over to the upload function? I've been reading the Puppeteer documentation and couldn't find any reason why this wouldn't work. Anyone knows why this is not valid?
The error message is saying that the value you're passing to child() is not a string.
Since you're calling:
storageRef.child(myOutput).put(myOutput)
That kind'of makes sense. My guess is that you want to pass a file name into child(), like:
storageRef.child("filename.pdf").put(myOutput)

How to handle the unhandelable errors?

I'm facing a problem with error handling in NodeJS,
While I was testing an application that I made, I noticed that if I passed undefined by mistake to the mongoose.connect() it will give you an error, unfortunately, this error is not being caught by the callback function, not either by try & catch blocks:
const envVariable = undefined;
try {
mongoose.connect(envVariable, (err) => {
if (err) return console.log("There was an error");
console.log("success");
});
} catch (error) {
console.log("Hah! I caught you");
}
You see the error is not being caught, see the output:
(node:36807) UnhandledPromiseRejectionWarning: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
at NativeConnection.Connection.openUri (.../nodeJS/tests/node_modules/mongoose/lib/connection.js:680:11)
at .../nodeJS/tests/node_modules/mongoose/lib/index.js:345:10
at .../nodeJS/tests/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (.../nodeJS/tests/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (.../nodeJS/tests/node_modules/mongoose/lib/index.js:1135:10)
at Mongoose.connect (.../nodeJS/tests/node_modules/mongoose/lib/index.js:344:20)
at Object.<anonymous> (.../nodeJS/tests/server.js:8:12)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
(Use `node --trace-warnings ...` to show where the warning was created)
(node:36807) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:36807) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I've faced these kinds of problems many times in my application, but this time I caught one here to open the discussion, how can I stop these kinds of errors to show in my face? and instead, handle them in a nice way?
handle = to catch when this problem happens, and to send a nice response to the client that there was a problem from the server side.
The moongoose.connect function takes the callback as its third argument, after connection string and options object. It returns a promise, which is getting rejected on the error, but you are never handling that.
The proper syntax is either
try {
await mongoose.connect(envVariable);
console.log("success");
} catch (error) {
console.log("Hah! I caught you");
}
or
mongoose.connect(envVariable).then(() => {
console.log("success");
}, (err) => {
console.log("Hah! I caught you");
});

How do ES6 async/await work with Observables and streams when they fail?

So, I've been trying to replicate this code:
https://github.com/sindresorhus/np/blob/370ef638344ab7115c956b75dc2823850084da39/index.js#L16
And it works. However, if the promise fails, I get an "unhandled promise" warning. Where does the catch statement belong on something like this if at all? Is there a better way to source information like this?
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
at makeError (/Users/daghassi/git/build/node_modules/execa/index.js:172:9)
at Promise.all.then.arr (/Users/daghassi/git/build/node_modules/execa/index.js:277:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:48454) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 5)
(node:48454) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
at makeError (/Users/daghassi/git/build/node_modules/execa/index.js:172:9)
at Promise.all.then.arr (/Users/daghassi/git/build/node_modules/execa/index.js:277:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:160:7)
(node:48454) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
(node:48454) UnhandledPromiseRejectionWarning: Error: Command failed: np patch --no-cleanup
Just put a try/catch block around your await call. This should be the same as if you would call a Promise and provide a catch function.
So if you have a function which getPromise() which returns a promise, you simply do this.
async function asyncFunction() {
try {
const result = await getPromise();
} catch (error) {
// Add your error handling code here
}
}

Categories