MySql - QSqlError is not caught - c++

Here's my code snippet:
try
{
if ( query.exec(query_str) == false ) {
err_desc = query.lastError().text().toStdString();
return RET_FAIL;
}
}
catch(QSqlError &e)
{
handleError(e);
}
I set a breakpoint inside handleError, but it seems this breakpoint was never reached when there is an error, with err_desc the following value:
MySQL server has gone away QMYSQL: unable to execute query
Why does it fail to catch the error ?

Because there's no error to catch.
If the query fails it return false and set a QSqlError, accessible via QSqlQuery::lastError(), but it doesn't raise an exception.
if ( query.exec(query_str) == false ) {
err_desc = query.lastError().text().toStdString();
handleError(query.lastError());
return RET_FAIL;
}

I suspect you are not getting an exception when the server has gone away.
There are other posts on handling this

Related

Where to see all possible error code of AwsServiceException?

I want to handle AwsServiceException based on the error code returned.
Where web page lists out all those possible error code? I cannot find it in the java doc.
https://sdk.amazonaws.com/java/api/2.0.0/software/amazon/awssdk/awscore/exception/AwsServiceException.html
private RuntimeException handleS3Exception(final AwsServiceException exception) {
if (exception.awsErrorDetails().errorCode().equals("NoSuchKey")) {
return new ObjectNotFoundException();
} else {
return exception;
}
}
Thank you!

SolrJ - NPE when accessing to SolrCloud

I'm running the following test code on SolrCloud using Solrj library:
public static void main(String[] args) {
String zkHostString = "192.168.56.99:2181";
SolrClient solr = new CloudSolrClient.Builder().withZkHost(zkHostString).build();
List<MyBean> beans = new ArrayList<>();
for(int i = 0; i < 10000 ; i++) {
// creating a bunch of MyBean to be indexed
// and temporarily storing them in a List
// no Solr operations performed here
}
System.out.println("Adding...");
try {
solr.addBeans("myCollection", beans);
} catch (IOException | SolrServerException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("Committing...");
try {
solr.commit("myCollection");
} catch (SolrServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code fails due to the following exception
Exception in thread "main" java.lang.NullPointerException
at org.apache.solr.client.solrj.impl.CloudSolrClient.requestWithRetryOnStaleState(CloudSolrClient.java:1175)
at org.apache.solr.client.solrj.impl.CloudSolrClient.request(CloudSolrClient.java:1057)
at org.apache.solr.client.solrj.SolrRequest.process(SolrRequest.java:160)
at org.apache.solr.client.solrj.SolrClient.add(SolrClient.java:106)
at org.apache.solr.client.solrj.SolrClient.addBeans(SolrClient.java:357)
at org.apache.solr.client.solrj.SolrClient.addBeans(SolrClient.java:312)
at com.togather.solr.testing.SolrIndexingTest.main(SolrIndexingTest.java:83)
This is the full stacktrace of the exception. I just "upgraded" from a Solr standalone installation to a SolrCloud (with an external Zookeeper single instance, not the embedded one). With standalone Solr the same code (with just some minor differences, like the host URL) used to work perfectly.
The NPE sends me inside the SolrJ library, which I don't know.
Anyone can help me understand where the problem originates from and how I can overcome it? Due to my unexperience and the brevity of the error message, I can't figure out where to start inquiring from.
Looking at your code, I would suggest to specify the default collection as first thing.
CloudSolrClient solr = new CloudSolrClient.Builder().withZkHost(zkHostString).build();
solr.setDefaultCollection("myCollection");
Regarding the NPE you're experiencing, very likely is due to a network error.
In these lines your exception is raised by for loop: for (DocCollection ext : requestedCollections)
if (wasCommError) {
// it was a communication error. it is likely that
// the node to which the request to be sent is down . So , expire the state
// so that the next attempt would fetch the fresh state
// just re-read state for all of them, if it has not been retired
// in retryExpiryTime time
for (DocCollection ext : requestedCollections) {
ExpiringCachedDocCollection cacheEntry = collectionStateCache.get(ext.getName());
if (cacheEntry == null) continue;
cacheEntry.maybeStale = true;
}
if (retryCount < MAX_STALE_RETRIES) {//if it is a communication error , we must try again
//may be, we have a stale version of the collection state
// and we could not get any information from the server
//it is probably not worth trying again and again because
// the state would not have been updated
return requestWithRetryOnStaleState(request, retryCount + 1, collection);
}
}

How to handle exceptions from StorageFile::OpenAsync when URI is bad

I have a section of code that correctly load images from http URIs when the URIs are valid but I cannot figure how to catch the exception OpenAsync throws when the URI is invalid (results in 404).
The problem is that when the lambda which contains the call to OpenAsync exits, the exception is thrown; the exception is not thrown while in the try/catch block.
The question is:
What is the correct way to catch the exception thrown by StorageFile::OpenAsync?
auto bm = ref new BitmapImage();
try {
Uri^ uri = ref new Uri("http://invaliduri.tumblr.com/avatar/128");
auto task = Concurrency::create_task(CreateStreamedFileFromUriAsync("temp-web-file.png", uri, nullptr));
task.then([] (StorageFile^ file) {
try {
return file->OpenAsync(FileAccessMode::Read);
} catch (...) {
// this does not catch the exception because the exception
// occurs after this lambda is exitted
}
}).then([bm](IRandomAccessStream^ inputStream) {
try {
return bm->SetSourceAsync(inputStream);
} catch (...) {
// this does not catch the exception because the exception
// occurs before this lambda is entered
}
});
} catch (...) {
// and obviously this would not catch the exception
}
I had this question 3 years later. I referenced this article. My scenario was, then, solved as follows,
#include<ppltasks.h>
...
auto file = ref new Windows::Foundation::Uri::Uri("ms-appx:///SomeFile.txt");
concurrency::create_task(Windows::Storage::StorageFile::GetFileFromApplicationUriAsync(data))
.then([](Windows::Storage::StorageFile^ f) {
return Windows::Storage::FileIO::ReadTextAsync(f);
})
.then([this](String^ s) {
this->someFileContent = s;
})
.then([](concurrency::task<void> t) {
try {
t.get();
} catch(Platform::COMException^ e) {
OutputDebugString(e->Message->Data());
}
});
This async task chain may fail in GetFileFromApplicationUriAsync or in ReadTextAsync throwing an exception. The key is that when thrown the only matching then(...) prototype is the final one. On entering the try block, task::get re-throws the exception caught by the concurrency classes on your behalf.
task.then([] (StorageFile^ file) { // this is where the exception is actually thrown
The exception is most likely thrown on this line because to be able to pass in the StorageFile to the lambda the .then is doing a non-explicit get() on the task. You're using what is called a "value continuation" while you probably want a "task continuation" and check for exceptions there.
auto task = Concurrency::create_task(CreateStreamedFileFromUriAsync("temp-web-file.png", uri, nullptr));
task.then([] (concurrency::task<StorageFile^> fileTask) {
StorageFile^ file;
try
{
file = fileTask.get(); // this is what actually throws if Uri is wrong
create_task(file->OpenAsync(FileAccessMode::Read)).then(/* ... */);
} catch (...)
{
// nothing to do here
}
});

How to set the exit status in a Groovy Script

We have a Groovy Script that exits with a status of 0 when everything worked and a non-0 status for different types of failure conditions. For example if the script took a user and an email address as arguments it would exit with a status of 1 for an invalid user, and a status of 2 for an invalid email address format. We use System.exit(statusCode) for this. This works fine, but makes the the script difficult to write test cases for.
In a test we create our GroovyShell, create our Binding and call shell.run(script,args). For tests that assert failure conditions, the System.exit() causes the JVM (and the test) to exit.
Are there alternatives to using System.exit() to exit a Groovy Script? I experimented with throwing uncaught exceptions, but that clutters the output and always makes the status code 1.
In our test cases I have also experimented with using System.metaClass.static.invokeMethod to change the behavior of System.exit() to not exit the JVM, but that seems like an ugly hack.
imho System.metaClass.static.invokeMethod looks fine. It's test, and hacking is fine here.
Also you can create your own wrapper around it, like:
class ExitUtils {
static boolean enabled = true
static exit(int code) {
if (!ExitUtils.enabled) {
return //TODO set some flag?
}
System.exit(code)
}
}
and disable it for tests.
Here is the technique we eventually used.
We can't just ignore a call to System.exit() since the script would continue to run. Instead we want to throw an exception with the desired status code. We throw a (custom) ProgramExitException when System.exit() is called in our tests
class ProgramExitException extends RuntimeException {
int statusCode
public ProgramExitException(int statusCode) {
super("Exited with " + statusCode)
this.statusCode = statusCode
}
}
then we intercept System.exit() to throw this exception
/**
* Make System.exit throw ProgramExitException to fake exiting the VM
*/
System.metaClass.static.invokeMethod = { String name, args ->
if (name == 'exit')
throw new ProgramExitException(args[0])
def validMethod = System.metaClass.getStaticMetaMethod(name, args)
if (validMethod != null) {
validMethod.invoke(delegate, args)
}
else {
return System.metaClass.invokeMissingMethod(delegate, name, args)
}
}
and lastly we have GroovyShell catch any ProgramExitException and return the status code from the run method.
/**
* Catch ProgramExitException exceptions to mimic exit status codes
* without exiting the VM
*/
GroovyShell.metaClass.invokeMethod = { String name, args ->
def validMethod = GroovyShell.metaClass.getMetaMethod(name, args)
if (validMethod != null) {
try {
validMethod.invoke(delegate, args)
} catch (ProgramExitException e) {
return e.statusCode
}
}
else {
return GroovyShell.metaClass.invokeMissingMethod(delegate, name, args)
}
}
Our tests can stay looking simple, we don't need to change anything in the scripts and we get the behavior we expect from running on the command line.
assertEquals 'Unexpected status code', 0, shell.run(script,[arg1, arg2])
assertEquals 'Unexpected status code', 10, shell.run(script,[badarg1, badarg2])

how to modify an exception object in Railo

try {
// some error
} catch (any e) {
e.extendedInfo = 'New extended info';
//throw(e);
//cfcatch.extendedInfo = 'New extended info';
rethrow;
}
When I (re)catch this exception the extendedInfo is not displayed. What I want to happen is the raised exception keeps all of its pre-catch properties including the original tagContext and line numbers etc but gets a new value for extendedInfo.
I've tried copying the attributes of e into a new attributeCollection and throwing that with throw(e) or <cfthrow attributeCollection="#e#" /> but then the context is changed and the error displays the wrong line of source code.
While I'm at it is there a way to to drop the topmost stack object so an exception appears to have been thrown from the calling context. ie:
function myRethrow(e) (
throw(e); // <!-- error is actually throw here BUT ...
)
myRethrow(e); // <-- error should appear to have 'happened' here
Using Railo 3.2
I think you can use throw function like this:
try {
try {
// some error
}
catch (any e) {
e.extendedInfo = 'New extended info';
throw(argumentCollection = e);
}
}
catch (any e) {
WriteDump(e);
}
Works for me.