When I tray to catch an http-post, It's ok for the XDMP-URI but not for the SVC-SOCCONN.
The XQuery stops, without any execution of the catch.
This is the extract of the XQuery with the try/catch :
let $return := try {
xdmp:http-post($uri,$options,$doc)
} catch ($e) {
xdmp:log("HTTP POST KO"),
<return><code>500</code></return>
}
The call is lazily evaluated so you’ll only get an error encountered during execution when you actually read the response.
I am not able to reproduce your issue. The following will produce SVC-SOCCONN and is caught by the try/catch, returning <return><code>500</code></return> and not the connection error.
let $doc := cts:search(doc(), cts:true-query())[1]
let $options := ()
let $uri := "http://10.255.255.1"
let $result := try {
xdmp:http-post($uri, $options, $doc)
} catch ($e) {
xdmp:log("HTTP POST KO"),
<return><code>500</code></return>
}
return $result
As #hunterhacker pointed out, lazy evaluation can sometimes cause some unexpected behaviors. It doesn't appear that is the issue here, unless there is a difference in a particular MarkLogic version (I am testing against the latest currently available, 10.0-8.2). If did want to ensure that an expression was not lazily evaluated, you could use xdmp:eager().
let $result := try {
xdmp:eager(xdmp:http-post($uri, $options, $doc))
} catch ($e) {
xdmp:log("HTTP POST KO"),
<return><code>500</code></return>
}
return $result
Related
In my scala and play code, a function throws an exception
case None => {
println("error in updating password info")
throw new Exception("error in updating password info") //TODOM - refine errors. Make errors well defined. Pick from config/env file
}
I want to test the above code but I don't know how to test that the Exception was thrown. The spec I have written is
"PasswordRepository Specs" should {
"should not add password for non-existing user" in {
val newPassword = PasswordInfo("newHasher","newPassword",Some("newSalt"))
when(repoTestEnv.mockUserRepository.findOne(ArgumentMatchers.any())).thenReturn(Future{None}) //THIS WILL CAUSE EXCEPTION CODE TO GET EXECUTED
val passwordRepository = new PasswordRepository(repoTestEnv.testEnv.mockHelperMethods,repoTestEnv.mockUserRepository)
println(s"adding password ${newPassword}")
val passwordInfo:PasswordInfo = await[PasswordInfo](passwordRepository.add(repoTestEnv.testEnv.loginInfo,newPassword))(Timeout(Duration(5000,"millis"))) //add SHOULD THROW AN EXCEPTION BUT HOW DO I TEST IT???
}
}
Thanks JB Nizet. I must confess I was being lazy! The correct way is either to use assertThrow or interrupt. Eg.
val exception:scalatest.Assertion = assertThrows[java.lang.Exception](await[PasswordInfo(passwordRepository.add(repoTestEnv.testEnv.loginInfo,newPassword)
)(Timeout(Duration(5000,"millis"))))
or
val exception = intercept[java.lang.Exception](await[Unit](passwordRepository.remove(repoTestEnv.testEnv.loginInfo))(Timeout(Duration(5000,"millis"))))
println(s"exception is ${exception}")
exception.getMessage() mustBe repoTestEnv.testEnv.messagesApi("error.passwordDeleteError")(repoTestEnv.testEnv.langs.availables(0))
public Connection executeUpdate() {
long start = System.currentTimeMillis();
try {
this.logExecution();
PreparedStatement statement = this.buildPreparedStatement();
this.connection.setResult(statement.executeUpdate());
this.connection.setKeys(this.returnGeneratedKeys ? statement.getGeneratedKeys() : null);
this.connection.setCanGetKeys(this.returnGeneratedKeys);
} catch (SQLException var7) {
this.connection.onException();
throw new Sql2oException("Error in executeUpdate, " + var7.getMessage(), var7);
} finally {
this.closeConnectionIfNecessary();
}
long end = System.currentTimeMillis();
logger.debug("total: {} ms; executed update [{}]", new Object[]{end - start, this.getName() == null ? "No name" : this.getName()});
return this.connection;
}
I'm wondering how to test an update failing. The query I'm using is:
update my_table set some_field=:some_value
where the_key = :the_key_value
And, immediately before executeUpdate() runs, I am deleting the record where the_key == "the_key_value".
Does anyone know the correct way to determine if the update failed?
Also, when I go to the javadoc and click on anything, I get:
CDN object Not Found - Request ID: c6a9ba5f-f8ea-46ae-bf7a-efc084971878-19055563
Is there a way to build javadoc locally?
EDIT: is the way to check this thru the use of Connection.getResult()? Does it return the number of records updated/inserted etc?
I went and RTFM which explained how to do this.
I use the Wordpress function $wpdb->get_results()
https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
It says:
"If no matching rows are found, or if there is a database error, the return value will be an empty array."
Then how can I know if the query failed OR if it's empty?
Use
$results=$wpdb->get_results($yoursql);
if (count($results)> 0){
//do here
}
But if you want to know if query failed
$wpdb -> show_errors ();
$wpdb -> get_results ($wpdb -> prepare($sql));
$wpdb -> print_error ();
Bit late to the party here but I'm just looking for the same thing. I've had a browse through the wp-db.php code on version 4.4.2.
On line 1422, inside the method flush() there's a bit of code which resets the last_error property:
$this->last_error = '';
This flush() method is called in the query() method on line 1693:
$this->flush();
The get_results() method calls query() on line 2322:
if ( $query ) {
$this->query( $query );
} else {
return null;
}
With this we can be pretty sure that more or less every time get_results() (Or get_row() too for that matter) is called, query() and flush() are both called, which ensures that last_error is set to the empty string before the query is executed.
So assuming the query runs (If it doesn't, null is returned - if the query is empty for example), last_error should contain an error message if the query was to fail for some reason.
Since last_error is flush()ed/reset each time, it should only contain an error for the last query that was run, rather than the last error for any query that had been run previously. With this in mind it should be safe to rely on last_error to determine whether something went wrong with the query.
$results = $wpdb->get_results($sql);
if (is_null($results) || !empty($wpdb->last_error)) {
// Query was empty or a database error occurred
} else {
// Query succeeded. $results could be an empty array here
}
Not the most intuitive in my opinion, but it seems to be sufficient.
Personally, I've written my own class around wpdb for my own benefit. This is my getResults() method.
public function getResults($query, $bindings = [])
{
// Prepare the statement (My prepare method inspects $query and just returns it if there's no bindings, otherwise it uses $wpdb->prepare()
$prepared = $this->prepare($query, $bindings);
// Execute the statement
$rows = $this->db->get_results($prepared, ARRAY_A);
// If an array was returned and no errors occurred, return the result set
if (is_array($rows) && empty($this->db->last_error)) {
return $rows;
}
// On failure, return false
return false;
}
Hope this helps.
Wpdb->get_results function from wordpress returns the result if successful otherwise it will return null. There can be many reasons if a query get failed.Refer in-depth article on debugging get_results() returning empty results here
Although you can use functions like wpdb->show_error() to check what was the last error after executing the sql query. sometimes this error returns empty
then try to use wpdb->last_query to check the final query that get formed.
I have I problem that I hope someone can help me with. I thought this code was right, but it will not work. Below is my code, it is a function for my CakePHP 2.2.2 site, the main aim of the code is to produce a menu system from database results. The problem is with my foreach loop, it will not loop. All $Key does is return the value of 2 (three records within the table at this time). So When I display / echo / debug $Menu, the only result I get is the last result stored within the database.
I know the SQL command is right, if that is debuged / echoed then all three results are displayed. The idea of this loop was to get it to count the results, so that I could run a check on a selected field. Where I am going wrong?
function MenuSystem() {
$this->loadModel('Menu');
$MenuSQL = $this->Menu->find('all', array('conditions' => array('active' => true)));
foreach ($MenuSQL as $Key=>$Value) {
$MenuSystem = $MenuSQL[$Key];
$this->Menu = $MenuSystem;
}
}
Many Thanks,
Glenn.
UPDATE :::
Below is my function, now my foreach loop now works, don't know what I was doing wrong, but I know think its working. You can see the print_r command that I am using for testing, if I use that, then all links from my database are printed / echoed on the screen and all works. But if I try and call the $this->Menu from another controller, then only the last record is echoed on the screen. I have moved the $this->Menu outside of the foreach loop, but it made no difference, with it inside the loop or outside, it still only echoes the last record and not all three. So what I am doing wrong?
function MenuSystem() {
$this->loadModel('Menu');
$SiteBase = '/projects/cake/';
$MenuSQL = $this->Menu->find('all', array('conditions' => array('active' => true)));
foreach ($MenuSQL as $key => $Value) {
$MenuAccessLevel = $MenuSQL[$key]['Menu']['roles_id'];
if ($MenuAccessLevel == 1) {
$Path = $MenuSQL[$key]['Menu']['path'];
$Title = $MenuSQL[$key]['Menu']['title'];
$MenuSys = "<a href=\" " . $SiteBase . $Path . " \">" . $Title ."";
} else {
print ("Admin");
}
//print_r($MenuSys);
} //End of Foreach Loop
$this->Menu = $MenuSys;
} //End of function MenuSystem
So When I display / echo / debug $Menu, the only result I get is the last result stored within the database.
You're setting the value of $this->Menu within the foreach, so when the foreach is complete it will take the last value iterated over.
If you want to find the number of records matching a condition, try:
$menuCount = $this->Menu->find('count', array(
'conditions'=>array('active'=>true)
));
$this->set(compact('menuCount'));
Edit: also, by setting the value of $this->Menu within the foreach, you're overwriting the Menu model variable. This is not a good idea.
Edit2: to get the counts of rows as grouped by some value, try:
$this->Menu->virtualFields = array('count' => 'count(*)');
$counts = $this->Menu->find('all', array(
'group'=>'Role',
'fields'=>array('Role', 'count'),
));
This generates SQL to have the results grouped by the Role column. Returned fields are the name of the role, and the number of rows having that value.
If you wanted to do it with a foreach loop instead, it might look like:
$menus = $this->Menu->find('all', array('fields'=>array('id', 'Role')));
$counts = array('user'=>0, 'admin'=>0);
foreach ($menus as $menu) {
$role = $menu['Menu']['Role'];
$counts[$role] += 1;
}
Let me be specific to my problem instead of generalizing it and confusing the audience. In my code I have set of network addresses (members of object-group actually) stored in individual arrays. I would like to compare whether Group A is a subset of Group B.
I am using Net::IP module to parse the IP addresses and use "overlaps" sub-routine to determine if an element (could be individual IP or a subnet) is a superset of another element.
The challenge I am facing is in returning success status only if each element of Group A, belongs to any one element of Group B.
Here is a way I thought of and proceeding to try to code it likewise:
$status = "match";
foreach $ip (#group_a) {
if a_in_b($ip,#group_b) #this sub-routine would be similar but with different comparison function
{
next;
}
else
{
$status = "no match";
last;}
}
Please suggest me if there is a better way to do it, would love to pick up new techniques. The above technique doesn't look sound at all! As I was searching for for some solutions, some references seem to suggest as if I could try using the smart match operator and overload it. But overloading is beyond my level of sophistication in perl, so kindly help!
EDIT:
Updated my code as per suggestion. Here is the working version (still need to add bits and pieces for error catching)
use Net::IP;
use strict;
use warnings;
my #subnet = ("10.1.128.0/24","10.1.129.0/24","10.1.130.0/24","10.1.108.4");
my #net = ("10.1.128.0/21","10.1.108.0/22");
sub array_subset {
my ($x, $y) = #_;
a_in_b ($_, #$y) or return '' foreach #$x;
return 1;
};
sub a_in_b {
my $node1 = shift(#_);
my #ip_list = #_;
for my $node2 (#ip_list) {
print $node2, "\n";
my $ip1 = new Net::IP ($node1) || die;
my $ip2 = new Net::IP ($node2) || die;
print "$node1 $node2 \n";
if ($ip1->overlaps($ip2)==$IP_A_IN_B_OVERLAP) {
return 1;
}
}
return "";
}
if (array_subset(\#subnet, \#net)) {
print "Matches";
}else
{
print "Doesn't match"
}
Overloading ~~ is a bit of overkill. I would suggest using List::MoreUtils:
use List::MoreUtils qw/all/;
if (all { a_in_b($_, #bignet) } #smallnet) {
# do something
};
Or just rewrite your own code as a sub, and in a more perlish way:
sub array_subset {
my ($x, $y) = #_;
a_in_b ($_, #$y) or return '' foreach #$x;
return 1;
};
# somewhere in the code
if (array_subset(\#subnet, \#net)) {
# do something
};