When failed to access something on the web (api, database), how would I stop executing the rest of the script and log the error in the log file? Well, and so that the visitor wouldn't see the exact cause but rather they would see my custom message (say, 'A bad thing just happened'). What steps do I need to take to arrange things?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
I would suggest you to go through this excellent article by David Walsh on custom error handling in PHP.
You can use set_error_handler() function for that.
There is a default function of PHP to log errors; error_log
Example from PHP.net:
.
More Resources:
This is also good article covering most of it related to error handling.
I generally like using Exceptions, in that kind of situation : it allows me to have all error-handling code at one place.
For instance, I'd use something a bit like this :
With that, all error-handling code is in the
catch
block -- and not scatterred accros my whole application.Note, though, that many PHP functions don't throw exceptions, and only raise a warning or an error...
For those, you could use
set_error_handler
to define your own error handler -- which could throw an Exception ;-)For instance, see the example on the manual page of
ErrorException
.Although this will work real fine for many errors/warnings, you should note that it will not work for
Parse Error
norFatal Error
:And I would never place any
die
norexit
in the middle of my code : that's, in my opinion, one of the worst possible way of dealing with errors.I would also configure my server / application so :
display_errors
toOff
.log_errors
anderror_log
.