开发者

Drupal - How to identify mysql error type and print custom error message

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'       开发者_Python百科     | 
|  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?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜