Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rojer's avatar
Level 1

How to catch custom MySQL exceptions through query builder?

Scenario:

  • Application can only run MySQL functions and stored procedures.
  • MySQL functions throw custom errors through procedure.
  • But query builder returns null when error occurs. And PDOException doesn't catch the error.

This works in Slim 3.

//lumen
$param = $request->input('param');
    $pdo = DB::connection()->getPdo();
    try {
        $sql = "SELECT `db_cbs`.`fn_test`(:param) AS result";
        $statement = $pdo->prepare($sql);
        $statement->execute([
            'param' => $param
        ]);
        $json = $statement->fetch(PDO::FETCH_ASSOC);
        $vars = json_decode($json['result'], true);
    } catch (\PDOException $e) {
        $vars = $e->getMessage();
    }
dd($vars);

//mysql function    
DELIMITER $$
CREATE FUNCTION `db_cbs`.`fn_test`(`p_param` INT)
RETURNS JSON
BEGIN
    CALL `db_cbs`.`sp_error`(40101);
        RETURN JSON_OBJECT('Foo', 'Bar');
END$$
DELIMITER ;

//mysql stored procedure
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_error`;
CREATE PROCEDURE `sp_error`(IN `p_code` INT(10))
BEGIN
    DECLARE `v_message` VARCHAR(255);

        SELECT `message`
        INTO `v_message`
        FROM `db_cbs`.`errors`
        WHERE `code` = `p_code`;

        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = `v_message`, MYSQL_ERRNO = `p_code`;
END$$
DELIMITER ;

Desired output is the message from exception.

0 likes
0 replies

Please or to participate in this conversation.