Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a 'friendly' error message for an exception

Tags:

exception

php

I am trying to connect to database and if there is anything wrong I throw an exception:

class Ex_cnt extends Exception{}
class Ex_slct extends Exception{}
$server = "localhost";
$usr = "root";
$pss = "*******";
$db = "learn";
try{
        $cnt = mysqli_connect($server,$usr,$pss);
        if(!$cnt){
            throw new Ex_cnt("wrong in database details");
        }
        $dbslct = mysql_select_db($db);
        if(!$dbslct){
            throw new Ex_slct("wrong database name");
        } 
}
catch(Ex_cnt $error_cnt){
        echo $error_cnt->getMessage();
}
catch(Ex_slct $error_slct){
        echo $error_slct->getMessage();
}

the problem is that this code shows the following error

Warning: mysqli_connect() [function.mysqli-connect]: (28000/1045): Access denied for user 'root'@'localhost' (using password: YES) in D:\xampp\htdocs\learn\index.php on line 10 Unable to connect

I want it to just show

Unable to connect

like image 406
Omar Moustafa Avatar asked Dec 07 '25 02:12

Omar Moustafa


1 Answers

You should turn off the display_errors in production environment.

ini_set('display_errors', 0);  
error_reporting(E_ALL); // While error reporting should remain at full force
like image 151
xdazz Avatar answered Dec 08 '25 14:12

xdazz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!