Groovy Gorm catch util.JDBCExceptionReporter error on save() - exception

I have a problem to catch util.JDBCExceptionReporter during save().
Code:
membership.withTransaction { status ->
try{
def membership = membership.findByUserId(userId)
if(!membership){
membership = new membership(userId: userId, email: userEmail, baseLevel: membership.findByName(membershipName.MEMBER)).save(flush: true)
}
}catch(org.springframework.dao.DataIntegrityViolationException e){
status.setRollbackOnly()
return false
}catch(all){
println "Insert Membership Exception.\n User Id: $userId\n " + e
}
When I create two thread to run this code, it throw a error:
2014-05-06 12:53:07,034 [Actor Thread 5] ERROR util.JDBCExceptionReporter - Duplicate entry 'test#gmail.com' for key 'email'
I don't want to show this error every time when their has two threads doing the same insert, because the first thread will go through and insert successfully, so I don't really care about second one.
My question is how to catch util.JDBCExceptionReporter?
Thanks.

Just guessing:
By default Grails doesn't throw exceptions when saving. To throw integrity exceptions you have to use save(failOnError: true).
So in this case, it's just an internal trace (util.JDBCExceptionReporter is not an exception).
In your case, instead of capturing exceptions I'd use validate before saving so you can get the integrity errors before trying to save.

As lsidroGH said, util.JDBCExceptionReporter is not an exception, it's a log message. It logs both SQLExceptions and SQLWarnings. There is no problem with your code, as one thread will have a save() call that returns true and the other thread's save() will get false.
If you don't want this message to show up in your logs, you will need to increase your log level for org.hibernate.util.JDBCExceptionReporter from ERROR to FATAL but this will potentially exclude valid exceptions you would want logged. Your best bet is to ignore it, as your code works.

Related

Session.add() does not add anything but also doesn't fail

I am trying to insert data into a database using the following code:
print("New Account: {}".format(new_acc))
session.add(new_acc)
if pers_inf is not None:
session.add(pers_inf)
print(session.dirty)
session.commit()
print("Number of Accounts after adding: {}".format(session.query(dbquery).filter_by(**param).count()))
session.close()
new_acc is not empty and session.add() does not throw any exception but session.dirty returns an empty IdentitySet and nothing is inserted into the database. Can anyone give me a hint on how to continue debugging here?

CakePHP 2.x - delete cascade failed, instead going to error -> showing a message [duplicate]

Am at a loss here. I need to know how to handle error messages in case of integrity constraint violations.
Meaning i want to show users some meaningful message instead displaying error messages like
Error: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
I need to capture these databse errors and just show messages like say
The item you are trying to delete is associated with other records
How do we deal with this.
i have found a refernce here : https://stackoverflow.com/a/8842963/576523
but i dont want to do a count check.
When we use the debug_kit plugin we can see that they have captured these values under the
variables tab. I need a way to do this or access these data from the debug_kit plugin.
Thankz.
You could also use try - catch
try {
$this->Item->delete();
} catch (Exception $e) {
$error = 'The item you are trying to delete is associated with other records';
// The exact error message is $e->getMessage();
$this->set('error', $error);
}
If you only want to catch a specific exception, specify the exception class in the catch block.Hope it will solve your problem.
try {
$this->Item->delete();
} catch (\PDOException $e) {
$error = 'The item you are trying to delete is associated with other records';
//exact error message $e->getMessage();
}
Using CAKEPHP3 -> CakePHP 3 - Catch Error
try
{}
catch (\PDOException $e)
{}
Solved like a charm ;) - \Exception or \PDOException

Safety of not catching SQL Exception

Let's say I have a program that puts email addresses into a database where the email attribute is a primary key.
If I have a duplicate email address, I could deal with it in two ways.
1) run a "select email from table" query. If the email is currently in there, don't add it.
2) don't check if email is in the table. catch(SQLException e), but don't print the stack trace, simply skip over it. This way, if I'm inserting a duplicate it effectively ignores it.
Granted with method 1, I'm only executing a simple select query (no joins or anything fancy) so performance isn't really a huge issue. But if I wanted to optimize performance, would method 2 be a viable, safe way of doing this?
So instead of running a "select ..." every time, I just add it.
Are there any safety issues with skipping over the exception?
Java Example (with JDBC):
try {
String sql = "insert into emails values(?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, email);
pstmt.execute();
return true;
}
catch(SQLException e) {
// e.printStackTrace(); // skip; don't print out error
return false;
}

Using Google Apps Script how to only retrieve objects from ScriptDb which possess property/key

Is it possible to query ScriptDb to return only those objects which possess a specific property/key?
results = db.query({key: db.not(null)}); // always triggers error "We're sorry, a server error occurred. Please wait a bit and try again."
results = db.query({key: db.not(undefined)}); // returns all objects in the database
and the reverse:
results = db.query({key: undefined});
results = db.query({key: null}); // both these cause an error on any of the ScriptDbResult methods "Your query object contains an invalid component."
Any thoughts?

Catching exceptions for "INSERT … ON DUPLICATE KEY UPDATE" workaround in ZF

ZF 1.9.5 here. Someone suggested catching exceptions to emulate ON DUPLICATE KEY UPDATE when using Zend_Db_Table.
Currently, I'm getting
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'i7dd30253497cfc0539d7c5830a926f7d' for key 'ukey'
..when using
$orderRow = $this->createRow();
$orderRow->ukey = $ukey;
$orderRow->save();
So, I want to catch that bugger with try / catch. On exception update , else insert.
But I don't know what to catch. Zend_Db_Exception? PDOException? Zend_Db_Adapter_Exception? I've tried several, but I don't think I got it.
Later edit.
This worked for me:
try {
$orderRow = $this->createRow();
$orderRow->ukey = $ukey;
$orderRow->$stepCol = time();
$orderRow->save();
} catch (Zend_Db_Statement_Exception $e) {
// on UNIQUE error, update
if ($e->getCode() == 23000) {
$orderRow = $this->fetchRow($this->select()->where('ukey = ?', $ukey));
$orderRow->$stepCol = time();
$orderRow->save();
}
}
Just look what exception is getting thrown like this:
try {
// query
} catch (Exception $e) {
var_dump(get_class($e));
}
That should tell you what kind of exception you need to catch because "Exception" will catch every type of exception, be it a ZF exception or a PDO exception or something completely different
It will throw a Zend_Db_Statement_Exception.
Regarding finding out what Exception is thrown, you could take a look at edorian's answer.