1 Error Handling in Stored Procedures
TopBuilding on Exception Handling and Stored Procedures basics, let's implement robust error handling patterns.
The Complete Pattern: Transaction + Error Handler + Logging
DELIMITER //
CREATE PROCEDURE process_order(
IN p_customer_id INT,
IN p_product_id INT,
IN p_quantity INT,
OUT p_status VARCHAR(50)
)
BEGIN
DECLARE v_stock INT;
DECLARE v_price DECIMAL(10,2);
DECLARE v_error_msg VARCHAR(500);
-- Error handler: rollback and log
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1 v_error_msg = MESSAGE_TEXT;
ROLLBACK;
INSERT INTO error_log (procedure_name, error_message, created_at)
VALUES ('process_order', v_error_msg, NOW());
SET p_status = CONCAT('ERROR: ', v_error_msg);
END;
START TRANSACTION;
-- Check stock
SELECT stock, price INTO v_stock, v_price
FROM products WHERE id = p_product_id FOR UPDATE;
IF v_stock < p_quantity THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Insufficient stock';
END IF;
-- Deduct stock and create order
UPDATE products SET stock = stock - p_quantity WHERE id = p_product_id;
INSERT INTO orders (customer_id, product_id, quantity, amount)
VALUES (p_customer_id, p_product_id, p_quantity, v_price * p_quantity);
COMMIT;
SET p_status = 'SUCCESS';
END //
DELIMITER ;This is the production pattern: (1) DECLARE HANDLER catches errors, (2) ROLLBACK undoes partial work, (3) Log the error for debugging, (4) Return a meaningful status to the caller. Every critical procedure should follow this template.
Key Takeaways
- Always wrap critical logic in START TRANSACTION + error handler
- Use
GET DIAGNOSTICSto capture the actual error message - Log errors to a table for post-mortem debugging
- Use
SIGNAL SQLSTATE '45000'for custom business rule violations