In a MySQL stored procedure, I am handling SQL exceptions with this:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SELECT "SQL exception occured." AS "SQL Exception";
SHOW ERRORS;
SHOW WARNINGS;
ROLLBACK;
END;
I know that an exception is being thrown because the SQL exception occured message is being displayed and the transaction gets rolled back. However, nothing is populated in the SHOW ERRORS orSHOW WARNINGS tables. Why is this, and how can I tell which SQL exception is being thrown?
Here is the SQL statement that’s causing the mystery exception:
SELECT IF(count(*) = 0, TRUE, FALSE)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA='myDatabase'
AND TABLE_NAME='exam';
EDIT:
Bohemian has informed me that the exception is being swallowed up by the handler. So how do I find out what the exception is and still rollback? In a java catch block, I can see the exception by using Exception.getMessage() or Exception.printStackTrace(). Is there a similar feature in MySQL?
When you declare a handler for
SQLEXCEPTION, the exception is consumed – it’s considered “handled” so there is no longer an “exception”.If your stored procedure flow depends on a particular exception, you must declare a handler for a particular SQLSTATE error code, eg
Actually, all handlers are actually of this form, because:
SQLEXCEPTIONis shorthand for the class ofSQLSTATEvalues that do not begin with'00','01', or'02'SQLWARNINGis shorthand for the class ofSQLSTATEvalues that begin with'01'NOT FOUNDis shorthand for the class ofSQLSTATEvalues that begin with'02'