Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-Friendly PHP Error Message

PHP is famous for displaying ugly error messages, though they are useful at times. I know I can hide error messages with

error_reporting(0);

That's fine, but it leaves the user completely in the dark as to what is going on. The page has stopped working and they don't know why. How can I display a simple message along the lines of "Sorry, there is an error. Please send an e-mail to the webmaster"?

It would be the same message for all errors, and I'm thinking of maybe popping up a javascript alert, but open to any other ideas.

like image 386
TrapezeArtist Avatar asked Mar 21 '23 19:03

TrapezeArtist


1 Answers

Implement an error and exception handler

You need to write a custom error handler like this. As you can see at the bottom, I am introducing a FATAL error. Here PHP does not spit any ugly error messages as you have quoted. It would just print Some Error Occured. Please Try Later.

<?php

set_error_handler( "log_error" );
set_exception_handler( "log_exception" );
function log_error( $num, $str, $file, $line, $context = null )
{

    log_exception( new ErrorException( $str, 0, $num, $file, $line ) );
}

function log_exception( Exception $e )
{
    http_response_code(500);
    log_error($e);
    echo "Some Error Occured. Please Try Later.";
    exit();
}

error_reporting(E_ALL);
require_once("texsss.php");// I am doing a FATAL Error here
like image 96
Shankar Narayana Damodaran Avatar answered Mar 31 '23 20:03

Shankar Narayana Damodaran