MySQL exception handler access exception being handled - mysql

I'm trying to rollback on an error, but still let the client receive the error. This might actually be impossible, unless there is a way to access the error in an exception handler.
It's possible to "throw" from an exception, i.e. it's possible to raise a signal:
CREATE PROCEDURE p ()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SIGNAL SQLSTATE VALUE '99999'
SET MESSAGE_TEXT = 'An error occurred';
END;
DROP TABLE no_such_table;
END;
But this sample code from the MySQL doc looks horrible, because it literally swallows all errors and jams them into one.
SHOW ERRORS seems relevant, but I don't see any way to work with it programmatically, e.g. SELECT Code FROM (SHOW ERRORS); is not possible.
Is this possible? Is there a better practice that I'm missing entirely?

Looks like RESIGNAL is what you are looking for.
RESIGNAL makes it possible to both handle an error and return the error information. Otherwise, by executing an SQL statement within the handler, information that caused the handler's activation is destroyed. RESIGNAL also can make some procedures shorter if a given handler can handle part of a situation, then pass the condition “up the line” to another handler.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`resig` $$
CREATE PROCEDURE `test`.`resig` ()
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
SELECT 'I executed something before throwing the error' as `this_works`;
RESIGNAL;
END;
SELECT foo FROM bar WHERE baz = 0;
END $$
DELIMITER ;
mysql> call resig();
+------------------------------------------------+
| this_works |
+------------------------------------------------+
| I executed something before throwing the error |
+------------------------------------------------+
1 row in set (0.00 sec)
ERROR 1054 (42S22): Unknown column 'foo' in 'field list'
mysql>

Related

Log the triggers, procedure, function errors in separate Table - printed on the console only

I want to log the errors/exceptions for the triggers, procedures and functions in separate Table.
"my code is look like this":
CREATE PROCEDURE SILENCE_DB.GET_WEB_APPLICATION_NAVIGATION(_xxx CHAR(32))
BEGIN
-- DECLARE THE EXCEPTION AND WORNING HANDLER
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS #_no = NUMBER, #row_no = ROW_COUNT;
GET DIAGNOSTICS CONDITION #_no
#sql_sat=RETURNED_SQLSTATE, #errMsg= MESSAGE_TEXT
-- to insert the error on my error table
CALL INSERT_ERROR_TABLE(........);
RESIGNAL;
END;
DECLARE CONTINUE HANDLER FOR SQLWARNING
GET DIAGNOSTICS #_no = NUMBER, #row_no = ROW_COUNT;
GET DIAGNOSTICS CONDITION #_no
#sql_sat=RETURNED_SQLSTATE, #errMsg= MESSAGE_TEXT;
-- to insert the error on my error table
CALL INSERT_ERROR_TABLE(........);
RESIGNAL; -- DECLARE THE NOT FOUND HANDLER
DECLARE CONTINUE HANDLER FOR NOT FOUND
BEGIN
-- NOTHING TO DO
END;
................... business code
................... business code
................... business code
................... business code
END;
but if I use the RESIGNAL/SIGNAL I get the error on console but no insert into the table ERRORS, and if I remove the RESIGNAL/SIGNAL I did not get the error on the console but the error is inserted on the ERRORS table !!!
SO anyone have suggestion how to achieve my target.
The solution as Solarflare said, using the MyISAM instead of InnoDB for the INSERT_ERROR_TABLE type

Why does this MySQL stored procedure not seem to execute its exit handler?

I have read the documentation on Exit Handlers and have found useful code ideas in relevant SO questions here and here amongst other places.
Nevertheless, calling the stored procedure below appears to complete OK and returns a TRUE value for the parameter success. when I know it is definitely not completing OK, not least because there was a syntax error in the body SQL (it was referring to a field that did not exist).
So the exit handler should have kicked in and returned FALSE for parameter success.
Can anyone help me to understand why a transaction that fails does not return the correct value for the parameter? (I suspect it has something to do with where I set success to true)
The actual SQL inside the transaction is not important to this question so I haven't shown it. Just assume that it might or might not successfully complete the transaction. It is the success or failure of that transaction that I want to detect through the parameter
DELIMITER $$
CREATE PROCEDURE do_thing (OUT success BOOLEAN)
DETERMINISTIC
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN SET success := FALSE; ROLLBACK; END; # rollback on any error
DECLARE EXIT HANDLER FOR SQLWARNING BEGIN SET success := FALSE; ROLLBACK; END; # rollback on any warning
START TRANSACTION;
< SQL that might cause an error >
< in my case it was referring to a field that didn't exist>
COMMIT;
SET success := TRUE;
END$$
DELIMITER ;
SEE DBFIDDLE
The first part is a copy of your code, it throws an error....
The second part is corrected, both DECLARE EXIT are moved within the block.
The third part is an example where #success will be set to false.

MySQL stored procedure - distinguish between note and error

I have a stored procedure that executes stored SQL.
However, the error-handler kicks-in and exits if the user attempts to execute
drop temporary table if exists t_person;
and 't_person' doesn't exist. I'm perfectly happy to generate an error when 'if exists' is not given, but how do I avoid an error for the earlier case (the error-code is unchanged)?
Here's my error handler:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
set #sql = 'select \'Invalid SQL or bad parameter resulting in invalid SQL\' as `Error`';
prepare stmt from #sql;
execute stmt;
END;
You could use a CONTINUE handler rather an an EXIT handler that catches MySQL error 1051 "Unknown table"...
DECLARE CONTINUE HANDLER FOR 1051 BEGIN END;
-or-
DECLARE CONTINUE HANDLER FOR SQLSTATE '42S02' BEGIN END;
EDIT
To catch a MySQL error in an exception handler, you need to specify the MySQL error number or the corresponding SQLSTATE to be caught. (You could specify a named condition, but that named condition has to resolve to a MySQL error number or SQLSTATE).
A syntax error would throw MySQL error 1064.
If a table foo exists, and you issue a
CREATE TEMPORARY TABLE IF NOT EXISTS `foo` (id INT);
That would throw MySQL error 1050.
To catch that error, declare another handler for that. Assuming you want to "swallow" the exception and continue processing...
DECLARE CONTINUE HANDLER FOR 1050 BEGIN END;
Reference: https://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html
The like p_person in the drop temporary table statement looks wrong to me; at least, I'm not familiar with using the LIKE keyword in a DROP TABLE statement.

How do I handle errors in a basic MySQL stored procedure?

Let's say I have a stored procedure:
DELIMITER $$
CREATE DEFINER=`root`#`%` PROCEDURE `SetupBlocks`(
IN myBlock VARCHAR(20)
)
BEGIN
INSERT INTO blocks (block)
VALUE (myBlock);
END
What if I made a mistake in my code and DB setup, and the column block only allows for 15 characters but someone using my application has been able to get 20 characters into myBlock? I would get an error similar to this for this example:
Error Code: 1406. Data too long for column 'block'
Is there some way to handle any error (not just this one) and then report it into a table called BlockSprocErrors for monitoring within MySQL and within the stored procedure itself?
Just looking for a very basic example by modifying my procedure above.
Here is what I ended up doing:
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS condition 1
#SQLState = RETURNED_SQLSTATE, #SQLMessage = MESSAGE_TEXT;
SELECT CONCAT('Database error occurred, state - ',#SQLState, '; error msg - ', #SQLMessage) INTO #errorString;
CALL Collectors_Errors
(#errorString,
'Collectors_InsertAlbum',
barcodeApp,
usernameApp);
END;

MySQL Stored Procedure Error Handling

I believe there is nothing currently available in MySQL that allows access to the SQLSTATE of the last executed statement within a MySQL stored procedure. This means that when a generic SQLException is raised within a stored procedure it is hard/impossible to derive the exact nature of the error.
Does anybody have a workaround for deriving the SQLSTATE of an error in a MySQL stored procedure that does not involve declaring a handler for every possible SQLSTATE?
For example - imagine that I am trying to return an error_status that goes beyond the generic "SQLException happened somewhere in this BEGIN....END block" in the following:
DELIMITER $$
CREATE PROCEDURE `myProcedure`(OUT o_error_status varchar(50))
MY_BLOCK: BEGIN
DECLARE EXIT handler for 1062 set o_error_status := "Duplicate entry in table";
DECLARE EXIT handler for 1048 set o_error_status := "Trying to populate a non-null column with null value";
-- declare handlers ad nauseum here....
DECLARE EXIT handler for sqlexception set o_error_status:= "Generic SQLException. You'll just have to figure out the SQLSTATE yourself...." ;
-- Procedure logic that might error to follow here...
END MY_BLOCK$$
Any tips?
PS I am running MySQL 5.1.49
I believe there is nothing currently available in MySQL that allows access to the SQLSTATE of the last executed statement within a MySQL stored procedure. This means that ... it is hard/impossible to derive the exact nature of the error.
Luckily that is not true.
SHOW ERRORS LIMIT 1 -- for SQL-state > 2
SHOW WARNINGS LIMIT 1 -- for SQL-state 1,2
Will show the last error or warning.
In order to prevent listing each and every error, you can handle a class of SQL-errors like so:
SQLWARNING is shorthand for the class of SQLSTATE values that begin with '01'.
NOT FOUND is shorthand for the class of SQLSTATE values that begin with '02'. This is relevant only within the context of cursors and is used to control what happens when a cursor reaches the end of a data set. If no more rows are available, a No Data condition occurs with SQLSTATE value 02000. To detect this condition, you can set up a handler for it (or for a NOT FOUND condition). An example is shown in Section 12.7.5, “Cursors”. This condition also occurs for SELECT ... INTO var_list statements that retrieve no rows.
SQLEXCEPTION is shorthand for the class of SQLSTATE values that do not begin with '00', '01', or '02'.
So to handle an exception, you need to only do:
DECLARE EXIT HANDLER FOR SQLSTATE SQLEXCEPTION .....;
Links:
http://dev.mysql.com/doc/refman/5.5/en/signal.html
http://dev.mysql.com/doc/refman/5.0/en/declare-handler.html
GET DIAGNOSTICS is available in 5.6.4
See
http://dev.mysql.com/doc/refman/5.6/en/get-diagnostics.html
I am doing the following workaround: using a SELECT to provocate an error. For example:
SELECT RAISE_ERROR_unable_to_update_basket;
This will result in the following error message (example):
ERROR 1054 (42S22): Unknown column 'RAISE_ERROR_unable_to_update_basket' in 'field list'
I am wrapping my call to a stored procedure in a try { ... } catch { ... } and now can handle this error. This will of course only work for provocating custom error messages from inside your stored procedure and will not handle any SQL or database errors, that might occur (because of duplicate-key entry). In the latter case, you might be able to workaround this using the solution of Johan.