How to catch and re-throw all errors in MySQL

nikdeapen picture nikdeapen · Oct 27, 2012 · Viewed 12.3k times · Source

I can't seem to find anywhere how to catch and re-throw any errors or warnings that can occur in a procedure.

What I want is the syntax to do the following:

create procedure myProcedure()
  begin

      declare exit handler for ANYTHING_WRONG_THAT_CAN_BE_CAUGHT_WARNINGS_INCLUDED
      begin
          rollback;
          RE_THROW THE_THING_THAT_WAS_CAUGHT;
      end;

      start transaction;
         -- do some stuff
      commit;
  end; //

The reason being that I want to force a rollback on an error or warning but leave it up to the client to decide what to do with the specific error.

The all-cap areas are the portions where I do not know what to put.

Thanks for any help!

Edit -------

I have since learned it is not possible to do what I have asked :'(.

Instead I have a single error for anything that goes wrong and used the following code:

declare exit handler for sqlwarning, sqlexception begin
    rollback;
    call error();
end;

(error() does not exist)

Answer

Marc Alff picture Marc Alff · Sep 18, 2013

To catch all SQL exceptions, use:

DECLARE EXIT HANDLER FOR SQLEXCEPTION

SQLWARNINGS can be used to catch warnings also.

Inside the exception handler, to raise the error or warning that was just caught, use:

RESIGNAL

See the documentation for the RESIGNAL statement:

http://dev.mysql.com/doc/refman/5.5/en/resignal.html

This is available since MySQL 5.5