im trying to scrap a website using pupeteer , this website has captcha and i use a 3rd party library/api to bypass the captcha
here is the simplified version of my code
const puppeteer = require('puppeteer');
const dbc = require('./dpc/deathbycaptcha');
async function init()
{
let page = launchPuppeteer();
try {
await page.goto(`https://www.example.com`, {timeout: 60000});
await captcha_element.screenshot({ path: setting.captcha , omitBackground: true, });
let captchaResult = await solve_captcha().catch((error)=> {throw new Error( error) });
log('ALL DONE');
}
catch (e) {
log('=====================ERROR============================');
log(e);
}
}
here is solve_captcha function
function solve_captcha(){
return new Promise(( resolve , reject )=>{
try
{
const client = new dbc.HttpClient('myUsername', 'myPassword');
client.decode({captcha: setting.captcha}, (captcha) => {
if (captcha) {
resolve(captcha['text']);
}
else
{
reject('error')
}
});
}
catch (e) {
reject(e.toString());
}
})
}
so sometimes i cant connect to captcha solving api due to down server or network problems , it would throw this error
C:\pathToProject\dpc\deathbycaptcha.js:218
throw new Error(err.message);
^
Error: read ECONNRESET
at ClientRequest.<anonymous> (C:\pathToProject\dpc\deathbycaptcha.js:218:15)
←[90m at ClientRequest.emit (events.js:310:20)←[39m
←[90m at Socket.socketErrorListener (_http_client.js:426:9)←[39m
←[90m at Socket.emit (events.js:310:20)←[39m
←[90m at emitErrorNT (internal/streams/destroy.js:92:8)←[39m
←[90m at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)←[39m
←[90m at processTicksAndRejections (internal/process/task_queues.js:84:21)←[39m
this error happens in the deathbycaptcha.js which i've required in my code with
const dbc = require('./dpc/deathbycaptcha');
here is the simplified version of the code in the in the deathbycaptcha.js which is cuzing the error
class HttpClient extends Client {
_call(arguments here) {
var options = {someoptions};
var form = new FormData();
const request = form.submit(options, (err, response) => {
if (err) {
console.log(err.toString())
throw new Error(err.message);
}
// more code here
}
}
so here is the problem , i have this code running inside 2 try/catch blocks
first in the caller function (init()) and second one in the solve_captcha function but none of them are able to catch this error and it will break all the code and the program will exit and i have to run it again
why cant i catch and handle this error in my code ?
Related
This question already has an answer here:
Discord.js v13 code breaks when upgrading to v14
(1 answer)
Closed last month.
Here is my code:
const Discord = require('discord.js');
const request = require('request');
// Set up the bot with a command prefix
const bot = new Discord.Client({
ws: {
intents: Discord.Intents.FLAGS.GUILDS |
Discord.Intents.FLAGS.GUILD_MESSAGES |
Discord.Intents.FLAGS.DIRECT_MESSAGES,
},
});
bot.commands = new Discord.Collection();
// Set up the Spotify API client
const spotifyClientId = 'myId';
const spotifyClientSecret = 'mySecret';
let spotifyAccessToken = null;
// Define a function for getting a new access token from the Spotify API
const getSpotifyAccessToken = () => {
return new Promise((resolve, reject) => {
request.post('https://accounts.spotify.com/api/token', {
auth: {
user: spotifyClientId,
pass: spotifyClientSecret,
},
form: {
grant_type: 'client_credentials',
},
}, (error, response, body) => {
if (error) {
reject(error);
} else {
resolve(JSON.parse(body).access_token);
}
});
});
};
// Define the command for playing a song
bot.commands.set('play', async (message, args) => {
// Get a new access token if necessary
if (!spotifyAccessToken) {
spotifyAccessToken = await getSpotifyAccessToken();
}
// Search for the song on Spotify
request.get({
url: 'https://api.spotify.com/v1/search',
headers: {
Authorization: `Bearer ${spotifyAccessToken}`,
},
qs: {
q: args.join(' '),
type: 'track',
},
}, (error, response, body) => {
if (error) {
console.error(error);
return;
}
const tracks = JSON.parse(body).tracks.items;
if (!tracks.length) {
message.channel.send('No songs found!');
return;
}
const track = tracks[0];
// Play the first matching song
const channel = message.member.voice.channel;
channel.join().then(connection => {
connection.play(track.preview_url);
}).catch(console.error);
});
});
// Log the bot in
bot.login('My Token');
However, when run, the code returns
TypeError: Cannot read properties of undefined (reading 'FLAGS')
at Object.<anonymous> (C:\Users\myusername\bot.js:7:30)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
I have
Updated discord.js (running at version 14.7.1)
Checked for syntax errors
Made sure there are no errors
I would like the code to successfully run and allow me to use my discord bot.
The actual result is that I am left with an error shown above.
Discord.js is installed and I am running the code using "node bot.js". Node.js is running at v16.14.2
Changed the intents property to the following worked for me:
[ Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildMessages, Discord.GatewayIntentBits.DirectMessages ]
I'm facing the same issue as mentioned here:
When trying to use stream and query a table without mentioning the schema.
Something like select * from table instead of select * from schema_name.table. I get the following error:
mssql uncaughtException RequestError: Invalid object name
I was able to log the error while listening to readStream.on('error') but it still throws an uncaughtException.
Software versions
"mssql": "^7.2.1",
"nodejs": "12.15.0"
Expected behavior:
Should be able to catch the uncaughtException
Actual behavior:
INFO: waaaaaa1
uncaughtException RequestError: Invalid object name 'employee'.
at handleError (.../node_modules/mssql/lib/tedious/request.js:388:15)
at Connection.emit (events.js:223:5)
at Connection.emit (.../node_modules/tedious/lib/connection.js:1071:18)
at Parser. (.../node_modules/tedious/lib/connection.js:1176:12)
at Parser.emit (events.js:223:5)
at Readable. (.../node_modules/tedious/lib/token/token-stream-parser.js:27:14)
Configuration:
import mssql from 'mssql';
try {
mssql.connect({
server,
port: Number.parseInt(port),
database,
user,
password,
options: {
encrypt: true, // for azure
trustServerCertificate: trustServerCertificate ? true : false // change to true for local dev / self-signed certs
}
})
.then(async client => {
const readStream = client.request();
readStream.stream = true;
const passThroughStream = new stream.PassThrough();
const writeStream = fs.createWriteStream(path.join(__dirname, './writeMe.json'));
readStream.on('error', () => log.info('waaaaaa1'));
passThroughStream.on('error', () => log.info('waaaaaa2'));
writeStream.on('error', () => log.info('waaaaaa3'));
readStream.pipe(passThroughStream).pipe(writeStream);
readStream.query(query);
})
// the promise error handler
.catch(() => {
log.info('waaaaaa4');
});
// the main sql error handler:
mssql.on('error', error => {
log.error('SQL error1', error);
});
// the main sql error handler:
client.on('error', error => {
log.error('SQL error2', error);
});
}
catch (err) {
log.info('catchhhh meee', err);
}
finally {
if(client){
client.close();
}
}
Finally resolved the issue using const readableStream = request.toReadableStream();
Full code:
const request = client.request();
const readableStream = request.toReadableStream();
const writeStream = fs.createWriteStream(path.join(__dirname, './writeMe.json'));
const passThroughStream = new stream.PassThrough();
readableStream.on('end', () => passThroughStream.end());
readableStream.on('error', (e) => log.info('waaaaaa1'));
readableStream.pipe(passThroughStream).pipe(writeStream);
request.query(query);
Try adding a catch handler to connect and more important to the mssql object as mentioned in the docs
mssql.connect({
// ...
})
.then(() => {
return readStream.query(query);
})
// the promise error handler
.catch(() => {
})
// the main sql error handler:
mssql.on('error', error => {
console.error('SQL error')
})
im trying to scrape some website , i use a service to bypass captcha using their library
here simplified version of my code
const dbc = require('./deathbycaptcha.js');
open_tab();
async function open_tab()
{
try {
const captcha = await solvecaptcha('xxxx' ,'somedomain' ) .catch(function (error) {throw new Error('caperror'); });
console.log('captcha is solved !');
}
catch(e)
{
console.log('--------ERRRO--------------------------');
console.log(e.message);
}
}
function solvecaptcha(datakey , url )
{
return new Promise(function(resoulve, reject){
const client = new dbc.HttpClient(config.captcha.username, config.captcha.password);
try
{
client.decode({extra: {type: 4, token_params: some_params}}, (captcha) => {
if (captcha) {
resoulve(captcha['text']);
else
reject('cant solve captcha!');
});
}
catch (e) {
reject('cant solve captcha!');
}
});
}
so it starts in the open_Tab function , i call solvecaptcha there and it returnes the solved captcha and its all good ... but sometimes there is a connection error in deathbycaptcha.js which will break the whole code
like if i close my internet connection and try this i get this error and the program crashes
C:\wamp64\www\domain_check\robot\DBC\deathbycaptcha.js:208
throw new Error(err.message);
^
Error: getaddrinfo ENOTFOUND api.dbcapi.me api.dbcapi.me:80
at ClientRequest.form.submit (C:\wamp64\www\domain_check\robot\DBC\deathbycaptcha.js:208:15)
at ClientRequest.emit (events.js:189:13)
at Socket.socketErrorListener (_http_client.js:392:9)
at Socket.emit (events.js:189:13)
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
i like to be able to control this exception so it wouldn't break the whole code , but no matter how many try/catch i use to control this ... ti wouldn't work and still breaks my code
and its this line that cuzes the problem
client.decode({extra: {type: 4, token_params: some_params}}, (captcha) => {
if (captcha) {
resoulve(captcha['text']);
else
reject('cant solve captcha!');
});
even though i've wrapped it inside try/catch its no use !
I am working on steam project. For that I am using node-steam module. I am stuct at login part.
I getting this exception while I am trying to logOn to steam account using node-steam
Exception as follow:
Uncaught TypeError: undefined is not a function MYAPP/node_modules/adm-zip/zipFile.js:8
Module.exports /MYAPP/node_modules/adm-zip/zipFile.js:8
module.exports /MYAPP/node_modules/adm-zip/adm-zip.js:25
handlers.(anonymous function) /MYAPP/node_modules/steam/lib/steam_client.js:252
SteamClient._netMsg`enter code here`Received /MYAPP/node_modules/steam/lib/steam_client.js:157
emitOne events.js:75
emit events.js:150
Connection._readPacket /MYAPP/node_modules/steam/lib/connection.js:50
emitNone events.js:65
EMIT events.js:147
emitReadable__ _stream_readable.js:408
emitReadable _stream_readable.js:402
readableAddChunk _stream_readable.js:157
Readable.push _stream_readable.js:109
onread net.js:510
Error: Disconnected
at SteamClient._disconnected (/MYAPP/node_modules/steam/lib/steam_client.js:186:24)
at emitOne (events.js:75:13)
at Connection.emit (events.js:150:7)
at TCP.close (net.js:457:12)
My source code is add follow:
var fs = require('fs');
var Steam = require('steam');
var crypto = require('crypto');
var serverlist = [] //server list here
Steam.servers = serverlist;
var steamClient = new Steam.SteamClient();
var steamUser = new Steam.SteamUser(steamClient);
steamClient.connect();
steamUser.on('updateMachineAuth', function (sentry, callback) {
console.log('writing to file sentry');
fs.writeFileSync('sentry', sentry.bytes);
callback({ sha_file: getSHA1(sentry.bytes) });
});
function getSHA1(bytes) {
var shasum = crypto.createHash('sha1');
shasum.end(bytes);
return shasum.read();
}
steamClient.on('connected', function () {
steamUser.logOn({
account_name: “XXXXXXXX”,
password: “XXXXXXXX”,
// un-comment this when providing secondary auth-code from email
auth_code: ‘XXX’,
sha_sentryfile: getSHA1(fs.readFileSync('sentry'))
});
});
steamUser.on('loggedOn', function () {
console.log('Logged in!');
});
steamClient.on('debug', function (response) {
console.log("debug: " + response);
});
steamClient.on('logOnResponse', function (response) {
console.log(">>logOnResponse");
console.log(response);
if (response.eresult == Steam.EResult.OK) {
console.log('Logged in!');
// Your code here
}
});
steamClient.on('error', function (error) {
console.log(error.stack);
alert("yes error");
});
steamClient.on('servers', function (servers) {
alert(servers);
// fs.writeFile('servers', JSON.stringify(servers));
});
steamClient.on('disconnected', function (s) {
alert(s);
});
Below are my installed versions.
Node Version: v10.8.0
NPM Version: 6.4.1
Steam Version: 1.4.0
OS: Mac
Please help me to resolve this issue .
The error that is being yield, undefined is not a function is happening because you are calling the function alert in node
That is not valid, as in node there is no function that is called like that, and since you have that function also in the errorHandler then the application dies.
If you were to delete the function alert of if you created and "alert" function that would console.log() what is happening the error should dissapear.
Try adding this function to your code or delete all of the alert functions:
const alert = () => {
console.log(arguments)
}
I'm newbie in NodeJS. I used Mongoose to check the existing item, if the item is not exist then will call another REST API, but it throw the error when running.
//check if hotel is existing
HotelModel.findOne({ name: hotel.name }, { name: 1 }, function (err, result) {
if (err) {
return
}
if (result) {
return
}
var address = await getHotelAddress(hotel.id) => throw error
});
and here is the error log:
var address = await getHotelAddress(hotel.id)
^^^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
It seems to can not call another task in findOne.
Thanks in advance.