- Catch All Errors & Exceptions In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP CATCH ALL ERRORS
- 1) BASIC PHP ERROR HANDLING
- 2) DISPLAYING A CUSTOM ERROR SCREEN
- 3) SAVE ERRORS TO THE DATABASE
- 3A) ERROR DATABASE TABLE
- 3B) ERROR TO DATABASE
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- 2 thoughts on “Catch All Errors & Exceptions In PHP (Simple Examples)”
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
- Catch All Errors & Exceptions In PHP (Simple Examples)
- TLDR – QUICK SLIDES
- TABLE OF CONTENTS
- PHP CATCH ALL ERRORS
- 1) BASIC PHP ERROR HANDLING
- 2) DISPLAYING A CUSTOM ERROR SCREEN
- 3) SAVE ERRORS TO THE DATABASE
- 3A) ERROR DATABASE TABLE
- 3B) ERROR TO DATABASE
- DOWNLOAD & NOTES
- SUPPORT
- EXAMPLE CODE DOWNLOAD
- EXTRA BITS & LINKS
- LINKS & REFERENCES
- INFOGRAPHIC CHEAT SHEET
- THE END
- 2 thoughts on “Catch All Errors & Exceptions In PHP (Simple Examples)”
- Leave a Comment Cancel Reply
- Search
- Breakthrough Javascript
- Socials
- About Me
Catch All Errors & Exceptions In PHP (Simple Examples)
Welcome to a quick tutorial on how to catch all errors and exceptions in PHP. Need to cast a net and capture all the errors to figure out what went wrong?
That covers the quick basics, but read on if you need detailed examples.
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP CATCH ALL ERRORS
All right, let us now get into examples of catching all errors and exceptions in PHP.
1) BASIC PHP ERROR HANDLING
Before we get into “catch errors”, here is a quick crash course on the default PHP error handling mechanisms. Yes, this is important. Some people skipped the basics, and wonder why “errors are not showing” when error reporting is turned off…
- Use error_reporting() to control what kinds of errors need to be reported – From everything E_ALL , to warnings E_WARNING , to boring notices E_NOTICE . I will leave a link to the full list below.
- log_errors and error_log to define if errors should be saved to a log file.
- Lastly, use display_errors to control if errors should be displayed on the screen during runtime.
- Not to be confused – We can turn off display_errors , but keep errors in a log file.
- But when error_reporting() is set to “don’t report any errors”, PHP will not show any errors nor save them into the log file.
P.S. All of these can be set in php.ini .
2) DISPLAYING A CUSTOM ERROR SCREEN
HAIYAA, AN ERROR HAS OCCURED.
The developers have been shamed and disowned from the family.
); // (C) THROW EXCEPTION throw new Exception("TEST ERROR!"); echo "This will not run";
- Save some data, so the user doesn’t lose everything. Or maybe even a possible “recovery” option.
- Show your custom error message.
3) SAVE ERRORS TO THE DATABASE
3A) ERROR DATABASE TABLE
CREATE TABLE `errors` ( `date` datetime NOT NULL DEFAULT current_timestamp(), `file` varchar(255) NOT NULL, `line` varchar(255) NOT NULL, `message` text NOT NULL, `trace` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `errors` ADD KEY `date` (`date`);
If you want to save the error into the database, here’s a quick dummy table you can work on.
3B) ERROR TO DATABASE
PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); // (C2) SAVE ERROR TO DATABASE $stmt = $pdo->prepare("INSERT INTO `errors` (`file`, `line`, `message`, `trace`) VALUES (. )"); $stmt->execute([ $ex->getFile(), $ex->getLine(), $ex->getMessage(), $ex->getTraceAsString() ]); // (C3) THEN SHOW YOUR CUSTOM ERROR MESSAGE echo "Mr. Stark, I don't feel so good."; >); // (D) THROW EXCEPTION throw new Exception("TEST ERROR!"); echo "This will not run";
This should be pretty self-explanatory – We save any errors into the database instead.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
2 thoughts on “Catch All Errors & Exceptions In PHP (Simple Examples)”
Thanks for sharing. Sorry if this is rude, but that snippet makes very little sense.
1) Read the tutorial carefully, it is about using set_exception_handler() to capture all errors and handle them gracefully.
2) The error message can be obtained from the exception itself – $ex->getMessage() . Also the file $ex->getFile() , line $ex->getLine() , and stack trace $ex->getTraceAsString() .
3) Notice how I deliberately left out the PHP error code $ex->getCode() ? That’s how little value it provided for debugging in years of my web development career. If you need it somehow – https://www.php.net/manual/en/errorfunc.constants.php
4) BAD idea to display the full error message, code, script name, and line number on a live system. Huge security risk.
5) Just show a simple “an error has occurred” to the user where possible. Or just the error message without file name, line, trace, and error code.
6) Keep error details internal – In a log file, or automatically send an email on critical stops.
7) What’s the point of glorifying the error details in a popup box? Are jQuery and Bootstrap really necessary? If you want to show an error on the screen, just do a getMessage()?> .
P.S. The error code is not totally useless. It can still be used for “graceful failures” such as shutting down on critical errors – if (CODE == 4096) < SHUT DOWN >.
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.
Catch All Errors & Exceptions In PHP (Simple Examples)
Welcome to a quick tutorial on how to catch all errors and exceptions in PHP. Need to cast a net and capture all the errors to figure out what went wrong?
That covers the quick basics, but read on if you need detailed examples.
TLDR – QUICK SLIDES
TABLE OF CONTENTS
PHP CATCH ALL ERRORS
All right, let us now get into examples of catching all errors and exceptions in PHP.
1) BASIC PHP ERROR HANDLING
Before we get into “catch errors”, here is a quick crash course on the default PHP error handling mechanisms. Yes, this is important. Some people skipped the basics, and wonder why “errors are not showing” when error reporting is turned off…
- Use error_reporting() to control what kinds of errors need to be reported – From everything E_ALL , to warnings E_WARNING , to boring notices E_NOTICE . I will leave a link to the full list below.
- log_errors and error_log to define if errors should be saved to a log file.
- Lastly, use display_errors to control if errors should be displayed on the screen during runtime.
- Not to be confused – We can turn off display_errors , but keep errors in a log file.
- But when error_reporting() is set to “don’t report any errors”, PHP will not show any errors nor save them into the log file.
P.S. All of these can be set in php.ini .
2) DISPLAYING A CUSTOM ERROR SCREEN
HAIYAA, AN ERROR HAS OCCURED.
The developers have been shamed and disowned from the family.
); // (C) THROW EXCEPTION throw new Exception("TEST ERROR!"); echo "This will not run";
- Save some data, so the user doesn’t lose everything. Or maybe even a possible “recovery” option.
- Show your custom error message.
3) SAVE ERRORS TO THE DATABASE
3A) ERROR DATABASE TABLE
CREATE TABLE `errors` ( `date` datetime NOT NULL DEFAULT current_timestamp(), `file` varchar(255) NOT NULL, `line` varchar(255) NOT NULL, `message` text NOT NULL, `trace` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ALTER TABLE `errors` ADD KEY `date` (`date`);
If you want to save the error into the database, here’s a quick dummy table you can work on.
3B) ERROR TO DATABASE
PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC ]); // (C2) SAVE ERROR TO DATABASE $stmt = $pdo->prepare("INSERT INTO `errors` (`file`, `line`, `message`, `trace`) VALUES (. )"); $stmt->execute([ $ex->getFile(), $ex->getLine(), $ex->getMessage(), $ex->getTraceAsString() ]); // (C3) THEN SHOW YOUR CUSTOM ERROR MESSAGE echo "Mr. Stark, I don't feel so good."; >); // (D) THROW EXCEPTION throw new Exception("TEST ERROR!"); echo "This will not run";
This should be pretty self-explanatory – We save any errors into the database instead.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SUPPORT
600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
LINKS & REFERENCES
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!
2 thoughts on “Catch All Errors & Exceptions In PHP (Simple Examples)”
Thanks for sharing. Sorry if this is rude, but that snippet makes very little sense.
1) Read the tutorial carefully, it is about using set_exception_handler() to capture all errors and handle them gracefully.
2) The error message can be obtained from the exception itself – $ex->getMessage() . Also the file $ex->getFile() , line $ex->getLine() , and stack trace $ex->getTraceAsString() .
3) Notice how I deliberately left out the PHP error code $ex->getCode() ? That’s how little value it provided for debugging in years of my web development career. If you need it somehow – https://www.php.net/manual/en/errorfunc.constants.php
4) BAD idea to display the full error message, code, script name, and line number on a live system. Huge security risk.
5) Just show a simple “an error has occurred” to the user where possible. Or just the error message without file name, line, trace, and error code.
6) Keep error details internal – In a log file, or automatically send an email on critical stops.
7) What’s the point of glorifying the error details in a popup box? Are jQuery and Bootstrap really necessary? If you want to show an error on the screen, just do a getMessage()?> .
P.S. The error code is not totally useless. It can still be used for “graceful failures” such as shutting down on critical errors – if (CODE == 4096) < SHUT DOWN >.
Leave a Comment Cancel Reply
Search
Breakthrough Javascript
Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!
Socials
About Me
W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.
Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.