How do I close the browser with puppeteer when the page throws an error?
async function fnGoogle(page) {
try {
//some code here
await page.goto('blablalba');
} catch (e) {
throw e
}
}
Use browser.close() to close the browser, but you'd have to do it before re-throwing the error in your catch-block:
} catch (e) {
await browser.close()
throw e
}
demo
Related
Im adding a duplicate to a mysql table and I want to handle elicited ER_DUP_ENTRY error comming back with a Try/Catch block but its just crashing anyway , is there any possible way to handle error and stop application from crashing using a try/catch block?
async function init() {
try {
connection.query(
'SOME INSERT QUERY',
(err, result, feilds) => {
if (err) throw err
console.log(result);
}
);
} catch (e) {
console.log(e);
}
}
init();
The node mysql-library does not support promises out of the box, which means query does not return a promise which you can await. So you can either wrap the query function in a promise yourself:
async function init() {
try {
const duplicateResult = await new Promise((resolve, reject) => {
connection.query(
'SOME INSERT QUERY',
(err, result, fields) => {
if (err) {
return reject(err);
}
resolve(result);
});
});
} catch (e) {
console.log(e);
}
}
or use util.promisify as Always Learning posted alternatively.
The problem is that connection.query returns undefined right away. Your catch is not involved because the call ends before the work is done and will call your callback function later. An exception that occurs during your callback is too late. You try/catch block has already completed.
You can use promisify to wait on it like this though:
const util = require("util");
function init() {
const queryPromise = util.promisify(connection.query);
return queryPromise('SOME INSERT QUERY')
.catch(e => {
console.log("It failed", e);
});
}
init().then(result => {
if (result) console.log("It worked", result);
else console.log("Aww, it didn't work");
});
I am very much struggling to find the solution to Error Snippet my problem. I am receiving errors.
for (address in accountAddress) {
try {
let code = await web3.eth.getCode(address)
//myCode.....
} catch (err) {
console.log(err)
}
}
My question is here i am creating pool for every API to get data from MySQL database, after query finish i am closing pool connection. Is there any performance issues if i do like this. what is best way to implement this.
Please excuse if i ask anything wrong, Thanks in advance.
firstapi: async (req, resp) => {
let connection;
try {
connection = await mysql.createPool(db);
let firstquery = "first query goes here";
const [firstapidata] = await connection.execute(verlaufevortagquery);
resp.json(firstapidata);
} catch (error) {
resp.status(500).json({ message: "Failed to execute query", Error: error });
}
},
secondapi: async (req, resp) => {
let connection;
try {
connection = await mysql.createPool(db);
let secondquery = "second query goes here";
const [secondata] = await connection.execute(verlaufevortagquery);
resp.json(secondata);
} catch (error) {
resp.status(500).json({ message: "Failed to execute query", Error: error });
}
}
Instead you can keep the connection open, there is no reason to open it every time
let connection;
connection = await mysql.createPool(db);
firstapi: async (req, resp) => {
try {
use connection.execute here
} catch (error) {
resp.status(500).json({ message: "Failed to execute query", Error: error });
}
},
secondapi: async (req, resp) => {
try {
use connection.execute here
} catch (error) {
resp.status(500).json({ message: "Failed to execute query", Error: error });
}
}
I'm getting
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 44): Error: fail
main.js
import { request } from './api'
async getData({ commit, state }, ids ){
try {
var x = await request(ids)
commit('getData', x.data)
} catch ( e ) {
console.log('request failed get',e.code,e.errno)
}
}
api.js
export async function request(type,url,ids){
axios.get('localhost/data')
.then(function (response) {
return Promise.resolve(response.data)
})
.catch(function (e) {
return Promise.reject(new Error('fail'))
})
}
How can I handle the promise rejection? Shouldn't the try catch block catch the error from the await function here?
You are mixing up async/await with promises. In api.js, there is no need to use the async keyword. The async keyword makes it so that anything you return from the function is wrapped in a promise, which you don't need, since axios.get returns a promise already.
Also, you forgot to actually return the promise from Axios, your request function just returns undefined.
Lastly, you don't have to return promises from the then and catch methods, just return a value, or throw an error.
If you rewrite the function like this it should work as expected:
export function request(type,url,ids){
return axios.get('localhost/data')
.then(function (response) {
return response.data
})
.catch(function (e) {
throw new Error('fail')
})
}
I have the sample code like this:
import net from 'net'
import B from 'bluebird'
class Test {
constructor() {}
async start() {
return await new B((resolve, reject) => {
try {
this.socketClient = net.connect(4724);
// Windows: the socket errors out when ADB restarts. Let's catch it to avoid crashing.
this.socketClient.on('error', (err) => {
if (!this.ignoreUnexpectedShutdown) {
throw new Error(`Android bootstrap socket crashed: ${err}`);
}
});
this.socketClient.once('connect', () => {
log.info("Android testbundle socket is now connected");
resolve();
});
} catch (err) {
reject(err);
}
})
}
}
let t = new Test()
await t.start()
But when i transform into es5 code, I got this error:
SyntaxError: src/test.js: await is a reserved word (34:0)
32 |
33 | let t = new Test()
> 34 | await t.start()
I know await should be corresponding to async, but start() method is marked as async, still got error.
How to solve it?