Wednesday, 25 July 2018

MySQL Error Handling

In this post, I am sharing the full demonstration on how to manage error/exception handling in the Stored Procedure of MySQL.
Whenever an exception is occurring in a stored procedure, it is very important to handle it by showing proper error messages.
If you do not handle the exception, there would be a chance to fail application with the certain exception in a stored procedure.
If you get an error in stored procedure, instead of an exit, you should continue without any error message. That means you can show any default or custom error code or message to the application/user.
MySQL provides Handler to handle the exception in the stored procedure.
Below is a full demonstration of a handler with examples:
How to declare handler in store procedure:
Syntax of Handler: 
Three type of Handler_Action:
  • CONTINUE
  • EXIT
  • UNDO
Type of Condition Value:
  • mysql_error_code
  • sqlstate_value
  • SQLWarning
  • SQLException
  • NotFound
How to write handler in stored procedure?
E.g.
The Above are four different handler examples. Now, I am going to insert a duplicate value into EmpID column.
In the above SP, I defined a CONTINUE handler with my custom exception message.
Now, call the above SP two times with same EmpID.
The first time, it will execute successfully, but the second time it will throw a custom error message.
As we defined CONTINUE handler, so it will just show an error message and CONTINUE to next part of the SELECT statement.
Let’s See,
Above are the two different calls with same EmpID value. The first call executes without any error message and the second call execute with an error message.
The resule of Second Call:
Continue1
Continue2
As we defined CONTINUE, so you can find two results in above image. One is our custom error message and second is the result of the defined SELECT statement.
The execution didn’t stop by error, and it continued for another part.
Now, check the EXIT handler:
Please modify your handler and replace CONTINUE by EXIT:
Call with the same parameter:
The Result is an only error message, and you cannot find two results as we defined EXIT to exit the code when an error occurred.
Exit1
The best practice is to create a output parameter and store 1 if any error occurred.
Application code has to check this output parameter is NULL or 1.
1 = Error.
NULL = No Error.
Below is a stored procedure for this:
Now call the above SP and select output parameter:
Now Results are:
IsError1
IsError2
Above is a simple demonstration of Error Handling in MySQL. You can also use SQLSTATE which shows default error messages of MySQL.

0 comments:

Post a Comment