With PHP and mysqli, is it possible to catch all mysqli errors in one place across all PHP scripts?

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-11 06:31:26

问题


Is it possible to catch all errors for mysqli calls in one place with one statement or do I have to check each mysqli call individually for an error?

I want to do something along the lines of:

if(mysqli_error_occurs_anywhere_in_web_app) {
    die('<html><head></head><body>database error</body></html>');
}

basically if a mysqli error occurs anywhere I want to output an html database error document. is this possible?


回答1:


You could alternately wrap all your queries on your own query function, instead of calling mysqli_query anywhere directly. For instance, in your own DB object. That way, if you ever have a need to switch DB implementations, you simply have to switch to a new DB object with a slightly different implementation of your query functions, instead of search/replacing gobs of calls to mysqli_query directly. And it also has the benefit of making error handing really easy and centralized.




回答2:


The first thing you need to ask yourself is whether you want to deal with all database errors in the same way. If you can't connect to your db, that's a serious error and may indicate your db server is down. In that case you may want some kind of urgent alert to be sent to you (if you're not already monitoring your DB another way). If a query fails due to an SQL syntax error it's probably a sign that you're not escaping input data or there is a bug in your code somewhere. In this case you probably want to log as much info as you can so you can debug/sort the problem later.

So, that aside, the first thing you probably need is to wrap your mysqli functions so that you can trap the various errors and deal with them how you need (either by writing your own DB class, or using your own functions) - the PHP docs give examples about how you might start to do this (mysqli docs). Or you might look into PDO which AFAIAA has more useful error handling (a mixture of exceptions and return values).

Then you will need one single point in the code to handle this. If you have some kind of front controller you may be able to put it there. Or you may be able to write your own custom exception handler to achieve what you need (set_exception_handler).

The quickest and dirtiest solution would be to write your own custom error handler to catch and parse all errors and act accordingly (possibly redirect to a db error page having logged any info appropriately). But I did say this was the dirtiest solution right?




回答3:


You could try setting a global exception handler and checking to see if the caught exception is of the proper class.



来源:https://stackoverflow.com/questions/9643289/with-php-and-mysqli-is-it-possible-to-catch-all-mysqli-errors-in-one-place-acro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!