[PHP-NOTES] note 130185 added to function.set-error-handler

[email protected] ("[email protected]")
Newsgroups php.notes
Message-ID <[email protected]>
While on this doc/page about PHP's "set_error_handler()", the reader needs to definitely be made aware of "set_exception_handler()", so I am trying to provide that benefit with this post along with a good/simple model to utilize for global error/exception-handling for a page/app that smartly routes how the page/app responds to errors and exceptions.

<?php

//Below code is written in a PHP 8.3 context.

error_reporting(E_ALL); //<--can restrict further/later as desired/needed.

ini_set('display_errors', '1'); /* <--Yes, do display errors so can understand what goes wrong prior to getting throwable-handling set up. Once your
Throwable-handling is in place, you control what gets displayed despite this setting. */

$in_dev_mode = true; //<--global var to help illustrate implementation.

/* Below function is the "global/catch-all" handler of Errors/Exceptions which all originate from class Throwable. */
function my_initial_exception_handler(Throwable $ref_throwable):never{
    $err_num = $ref_throwable->getCode();
    $err_msg = $ref_throwable->getMessage();
    $file_path = $ref_throwable->getFile();
    $line_num = $ref_throwable->getLine();

    //Log the error regardless of whether in dev-mode...
    $str_for_logger = "err_msg='{$err_msg}'; file_path='{$file_path}'; err_num='{$err_num}'; line_num='{$line_num}'";
    error_log($str_for_logger, 3, "/path/to/error.log");

    //But selectively control what goes to screen...
    global $in_dev_mode;
    if($in_dev_mode===true){
        $str_display_to_browser = <<<GHUJ87TGH
        <div style="color: red; font-size: x-large;">
            err_msg='{$err_msg}'
            <br>
            file_path='{$file_path}'
            <br>
            err_num='{$err_num}'
            <br>
            line_num='{$line_num}'
        </div>
GHUJ87TGH;
    }else{
        $str_display_to_browser = 'Sorry, but an error/exception occurred.';
    }

    echo $str_display_to_browser;
    exit;
} //end fn

set_exception_handler('my_initial_exception_handler');

/*
--Internal PHP functions mainly use Error reporting, while only modern Object-oriented extensions use exceptions.
  But...reported-errors can be converted to exceptions using class 'ErrorException' (the technique only works with non-fatal errors).
--Recall also that the fn registered using 'set_error_handler()' gets called when fn trigger_error() is called in PHP code,
  making it essential to have the below 'set_error_handler()' registration and error-reporting conversion in-place.
*/
set_error_handler(
    function($severity, $message, $file, $line){
        //The below "@noinspection" directive/annotation is optional and spares you from IDE warnings:
        /** @noinspection PhpUnhandledExceptionInspection */
        throw new ErrorException($message, 0, $severity, $file, $line);
    }
);

/*
...and below is where your php page/app begins its work...

Once you get your auto-loading set up, or your require() calls in-place to bring in your custom classes, you can call function "set_exception_handler()" again to switch over to your better/more robust handler.
*/

echo 'Hello World and welcome to my amazing app.';
?>

Know also that if you are "raising errors" in your PHP code, you likely no longer want to do it using "trigger_error()"--but you of course can if you choose, and if you do, the code above handles getting things switch over to a thrown Exception. The new way is to use the newer technique of using:
"throw new Exception('error message goes here.');". And do not forget, one may benefit from extending the Exception class with one's own custom Exception class and throwing it instead.
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.84.18 (proxied: 96.60.59.42)
----
Manual Page -- https://php.net/manual/en/function.set-error-handler.php
Edit        -- https://main.php.net/note/edit/130185
Del: integrated  -- https://main.php.net/note/delete/130185/integrated
Del: useless     -- https://main.php.net/note/delete/130185/useless
Del: bad code    -- https://main.php.net/note/delete/130185/bad+code
Del: spam        -- https://main.php.net/note/delete/130185/spam
Del: non-english -- https://main.php.net/note/delete/130185/non-english
Del: in docs     -- https://main.php.net/note/delete/130185/in+docs
Del: other reasons-- https://main.php.net/note/delete/130185
Reject      -- https://main.php.net/note/reject/130185
Search      -- https://main.php.net/manage/user-notes.php
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.