1

I'm developing a Drupal module. There is a table called currency. The currency_code column is set to be UNIQUE. When I try to enter a duplicate entry, drupal automatically shows an error message like this:-

.-------------------------------------------------------------------------.
|  user warning: Duplicate entry 'USD' for key 'currency_code'            | 
|  query: INSERT INTO currency(currency_id, currency_name, currency_code) |
|  VALUES (NULL, 'US Dollar', 'USD') in /xxx/currency/currency.admin.inc  |
|  on line 106.                                                           |
.-------------------------------------------------------------------------.

Obviously I cannot just let the user see this error. Instead I want to print a custom error message indicating the reason of the error (duplication of unique value in this case). So my question is how to I identify what is causing the error and display it in a user friendly manner (probably using drupal_set_message()).

Is there any way I can save the error message string in a variable, so that I can parse it in the background and print a cusom message?

3 Answers 3

4

Drupal's database abstraction layer has a function called db_error which wraps mysql_errno and returns the MySQL error number of the last query.

Sign up to request clarification or add additional context in comments.

Comments

2

Firstly, you should interpret the error via its number, not by parsing the string, which is subject to change.

Secondly, it would be better practice to anticipate this problem and handle it better. If the problem is ignorable for example, perhaps INSERT . . . ON DUPLICATE UPDATE would be more appropriate. If it's not ignorable, perhaps the appropriate way would be to check and display an appropriate message, rather than relying on the query to fail.

Comments

1

You should use devel's dprint_r($array) function, as well as other functions it provides to display user-friendly error messages.

If you just want to hide it, set Error_reporting in admin to LOG.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.