I have put an if else condition in selenium webdriver node.js to check if a string contains an "Add New" string, but I am getting the error Unable to locate element: // *[contains(text(),'Add New')]
Here is the code:
if (driver.findElement(By.xpath("// *[contains(text(),'Add New')]"))) {
reject(new Error("This is an error"));
} else {
resolve(true);
}
Try this one
string bodyText = driver.findElement(By.xpath("//body")).text;
if (bodyText.Contains('Add New')) {
reject(new Error("This is an error"));
} else {
resolve(true);
}
Or
try {
driver.findElement(By.xpath("// *[contains(text(),'Add New')]"));
reject(new Error("This is an error"));
}
catch (ElementNotFound e) {
resolve(true);
}
Note: the first one should be significantly faster, since the second approach would try to wait for implicit wait amount of time before it throws the error for the element not being found.
Related
I have got a function in a service that needs to get a value of a new or already existing object from the database and save it.
Issue is that name attribute of this object needs to be unique.
I know i can just create a .some() function over all database objects to check if i can enter this new value but its probably very unoptimal.
I would like to create somethign like this (below) but i have no idea what to do next:
const newObject = await this.repository
.save({
...newObjectDto,
})
.catch(err => {
if (err instanceof QueryFailedError) {
// some code for err checking to make
// sure i only catch the unique_violation
// error and then throw error
}
});
Error code for unique_violation is 23505. You can check out the full list of error codes returned by PostgreSQL here.
In order to catch a unique constraint violation, you can do:
try {
const newObject = await this.repository
.save({
...newObjectDto,
})
}
catch(err) {
if (err instanceof QueryFailedError) {
if(err.code === '23505') {
console.log(`Unique constraint ${err.constraint} failed`);
throw err;
}
}
}
How do you import sequelize errors?
I want to use specific errors like SequelizeUniqueConstraintError) for error handling.
try {
query...
} catch(e){
if (e instanceof SequelizeUniqueConstraintError) {
next(new ResourceError(e.toString(), 401))
} else {
next(new ResourceError(e.toString(), 500))
}
}
I'm getting SequelizeUniqueConstraintError is not defined, but I can't seem to navigate through the sequelize instance to find any error classes?
Check the source code of SequelizeUniqueConstraintError. The class named UniqueConstraintError. The SequelizeUniqueConstraintError is the value of name property. It's NOT a JavaScript class. So you should use UniqueConstraintError.
E.g.
import { UniqueConstraintError } from 'sequelize';
try {
throw new UniqueConstraintError({ message: 'test unique constraint' });
} catch (e) {
if (e instanceof UniqueConstraintError) {
console.log(401);
} else {
console.log(500);
}
}
The execution result:
401
package version: "sequelize": "^5.21.3"
I'm new to NodeJs and code I'm working with is using Q framework for promises.
And it seems that I don't understand the 'Q' framework too well, I'm running into a case when promises are returning too early.
Here is my code:
BridgeInfo.getBridgeInfo(exten)
.then(function processBridgeInfo(bridge_info) {
console.log("Nitesh -- bridge info is back, yay");
if (bridge_info !== undefined) {
conf_bridge = new VoxConfBridge(ari);
conf_bridge.init(bridge_info);
/**Add the bridge to the bridgeList**/
bridgeList[conf_bridge.bridge.id] = conf_bridge;
console.log("Bridge ID to register is "+ conf_bridge.bridge.id);
self.registerEvents(conf_bridge.bridge);
conf_bridge.registerUser(event, false, channel);
} else {
console.log("Unknown extension [" + exten + "] blocking it");
ChannelDriver.blockChannel(ari, channel.id);
}
})
.catch(function handleError(err) {
console.error("Nitesh -- [voxbridgemanager] error occured "+err);
});
The above code calls a function getBridgeInfo, this function is supposed to do some DB queries and return the result.
Here is the code in getBridgeInfo
BridgeInfo.getBridgeInfo = Q.async(function(bridge_identifier) {
console.log("Nitesh -- Getting the bridge info for ["+ bridge_identifier + "]");
if (bridge_identifier !== undefined) {
db.getConfBridgeProfile(bridge_identifier)
.then(function processBridgeProfile(result) {
if (result !== undefined) {
console.log("Nitesh -- Bridge Info is "+ JSON.stringify(result));
var bridge_info = new BridgeInfo();
bridge_info.init(result)
.then (function bridgeInfoInitDone() {
return bridge_info;
})
.catch( function handleError(err) {
console.error("Nitesh ---[bridgeInfoInit] Error is "+ err);
});
}
else {
console.log("Can't find any bridge profile for this identifier ["+ bridge_identifier + "]");
}
}, function handleError(err) {
console.error("Failed to retrieve bridgeInfo");
});
} else {
console.error("Received an invalid identifier");
}
});
**When I run this code, I see that in my main code,which calls getBrigeInfo, it hits its catch error handler even before getBRidgeInfo has executed completely, getBridgeInfo's SQL query results appear afterwards.
I think the way I'm using promises isn't being done correctly, any explanations please
Your missing the key part of what promises can do.
You should not need to do any catch statements in your getBridgeInfo. You should return the whole promise that gets the SQL data... and handle it in your first block of code BridgeInfo.getBridgeInfo(exten)
Assuming that db.getConfBridgeProfile(bridge_identifier); returns a promise
Example:
BridgeInfo.getBridgeInfo = function(bridge_identifier) {
console.log("Nitesh -- Getting the bridge info for ["+ bridge_identifier + "]");
if (bridge_identifier !== undefined) {
return Q.fcall(function () {
throw new Error("Received an invalid identifier");
});
}
return db.getConfBridgeProfile(bridge_identifier);
}
I've also seperated out your process query... keep things simple.
BridgeInfo.processBridgeProfile = function(result) {
if (result !== undefined) {
console.log("Nitesh -- Bridge Info is "+ JSON.stringify(result));
var bridge_info = new BridgeInfo();
return bridge_info.init(result);
}else{
return Q.fcall(function () {
throw new Error("Can't find any bridge profile for this identifier ["+ bridge_identifier + "]");
});
}
Return promises and handle the catch in the main function. Your getting stuck in handling a catch, the SQL results are not getting returned like they should.
Call:
BridgeInfo.getBridgeInfo(bridge_identifier).then(function(result){
return BridgeInfo.processBridgeProfile(result)
}).then(function(){
//Do the rest here
}).catch(function(){
//One catch to rule them all :)
});
I am using the sftps NPM to connect to a SFTP server using username/password authentication and upload a file. This works beautifully when successful; however, if provided invalid authentication information, after several minutes it emits an ECONNRESET error which crashes my entire application.
Looking at the source of the sftps module, it appears to use child_process.spawn to run the shell commands, and looks like it should be capturing any errors gracefully:
var sftp = spawn(shellCmd, shellOpts);
var data = "";
var error = "";
sftp.stdout.on('data', function (res) {
data += res;
});
sftp.stderr.on('data', function (res) {
error += res;
});
function finished(err) {
error = error.split('\n').filter(function(line) {
if (/^Connected to /.test(line)) return false;
return true;
}).join('\n');
data = data.split('\n').filter(function(line) {
if (/^sftp> /.test(line)) return false;
return true;
}).join('\n');
if (callback) {
if (err) {
callback(err, { error: error || null, data: data });
} else if (error) {
callback(null, { error: error, data: data });
} else {
callback(null, { error: null, data: data });
}
callback = null;
}
}
sftp.on('error', finished);
sftp.on('exit', function (code) {
if (code === 0) {
finished();
} else {
finished('Nonzero exit code: ' + code);
}
});
sftp.stdin.write(cmdString, 'utf8');
It looks like it has hooked into the stderr stream as well as capturing the error and exit events on the sub-process.
What else can I do to capture this ECONNRESET error and log it without killing the application?
Don't know if you're having the same problem that I was having, but I eventually solved it by attaching an event to stdin.on("error"). You could try this to see if that's the problem:
sftp.stdin.on("error", function (e)
{
console.log("STDIN ON ERROR");
console.log(e);
});
In the following code I'm able to catch the exception and print it but for some reason my program breaks there and it makes me to restart the application. Can't I handle it gracefully with out restarting it?
var checkRecordId = function (recordId)
{
if (recordId < 0)
throw new Error ("Record Id can not be 0 or less");
}
var getReport = function (dateRange , recordId)
{
try
{
checkRecordId (recordId);
}
catch (err)
{
console.log (err);
}
}