Create your own MySQL error message

In MySQL, how to create your own message for this error message:

Cannot delete or update parent row: foreign key constraint is not satisfied ( database. jenis_fasum, CONSTRAINT jenis_fasum_ibfk_1FOREIGN KEY ( id_kategori) LINKS kategori_fasum( id_kategori))

Perhaps with a trigger? Can someone give an example?

thanks for the help

+5
source share
1 answer

I don’t think it can be done in TRIGGER, but it can be done using a stored procedure in MySQL 5.5.

The default error message is displayed here:

mysql> INSERT INTO area SET location_id = 'invalid';
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`rates`.`area`, CONSTRAINT `area_ibfk_1` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`))

mysql> SHOW ERRORS;
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Level | Code | Message                                                                                                                                                              |
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Error | 1452 | Cannot add or update a child row: a foreign key constraint fails (`rates`.`area`, CONSTRAINT `area_ibfk_1` FOREIGN KEY (`location_id`) REFERENCES `location` (`id`)) |
+-------+------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

And here is our stored procedure:

DROP PROCEDURE IF EXISTS test1;

DELIMITER //

CREATE PROCEDURE test1()
DETERMINISTIC
MODIFIES SQL DATA
SQL SECURITY INVOKER
BEGIN
  DECLARE EXIT HANDLER FOR SQLSTATE '23000'
  BEGIN
    SIGNAL SQLSTATE '23000' SET 
      MYSQL_ERRNO = 1452,
      MESSAGE_TEXT = 'Yo! Error 23000!';
  END;

  INSERT INTO area SET location_id = 'invalid';
END;
//

DELIMITER ;

And here is our custom error message:

mysql> CALL test1();
ERROR 1452 (23000): Yo! Error 23000!

mysql> SHOW ERRORS;
+-------+------+------------------+
| Level | Code | Message          |
+-------+------+------------------+
| Error | 1452 | Yo! Error 23000! |
+-------+------+------------------+
1 row in set (0.00 sec)

By the way, why do you need this?

+2

All Articles