I am currently writing a web app in PHP and have decided to use exceptions (duh!).
I could not find an answer to whether putting try and catch blocks in all functions would be considered bad code.
I am currently using Exceptions to handle Database errors (Application errors are handled via a simple function which just adds them to an array and then they are displayed to the user). The try blocks are placed on all functions which require a database connection.
The code in question is:
public function db_conn_verify()
{
if(!isset($this->_mysqli)){
throw new Exception("Network Error: Database connection could not be established.");
} else {
return Null;
}
}
And an example function using this code:
public function get_users() {
try {
$this->db_conn_verify();
//Rest of function code
return True;
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
return False;
}
}
Also would it be better to extend the Exception class and then use that new Exception class to handle application errors?
Thanks
I suggest to you to use something like this:
public function get_users() {
try {
if( !isset($this->_mysqli) ) {
throw new Exception("Network Error: Database connection could not be established.");
}
//Rest of function code
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
}
I prefer to use my exends of Exception, but is the same. For exdending exception you can see the PHP documentation to Example #5
EDIT: For an immediate use of try-catch on database connection error you can try this:
try{
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
throw new Exception("Network Error: Database connection could not be established.");
}
} Catch(Exception $e) {
Core::system_error('function get_users()', $e->getMessage());
}
Related
This code triggers my editor's intelephense for error:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name']);
} catch (\exception $e) {
throw new \exception($e->getMessage(), $e->getCode());
}
}
Expected 6 arguments. Found 4.intelephense(10005)
would it be fine if I just use:
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'],null,null);
Thank you all for answering; also deceze who corrected me on wrong way to catch exception;
this is edited code:
/**
* Connect to database
*/
public function link() {
global $config; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
return new \mysqli($config['db_hostname'], $config['db_username'], $config['db_password'], $config['db_name'], ini_get('mysqli.default_port'), ini_get('mysqli.default_socket'));
} catch (\exception $e) {
echo 'Cannot connect to a database server'; die();
}
}
note ,this is for withing the class using namespaces...
The intelephense plugin uses the stubs from PhpStorm. The author already submitted a PR to fix this (and other functions with optional parameters): https://github.com/JetBrains/phpstorm-stubs/pull/520.
As soon as that's merged and the stubs are updated, you should no longer receive the problem reported in vscode.
There should be no need to change your constructor call, it is valid code and will execute without problems.
I am trying to use exception handling in case a file does not exists. For example when I run the model method and pass a string usr (which I know there is no file with that name) . It gives me the following error message
Fatal error: Uncaught exception 'Exception' with message 'Usr.php was not found' in /app/core/controller.php on line 14
I can't figure out whats wrong here. Can someone please help me figure this out?
Below is my code. Thanks alot!
class Controllers{
public function model($model){
if(!file_exists("../app/models/".$model.".php")) {
throw new exception("{$model}.php was not found");
}
try {
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
You can't throw an exception without catching it; this automatically causes the PHP script to crash. So, you need to surround your entire function in the try-catch block, or the "model not found" exception will be uncaught. Your code should be something like this:
<?php
class Controllers {
public function model($model){
try {
if (!file_exists("../app/models/".$model.".php")) {
throw new Exception("{$model}.php was not found");
}
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
Never mind guys! I found out I needed to use the try/catch blocks in the file where my method is being invoked
Example..
class Home extends Controllers{
public function index($name = ""){
try{
$user = $this->model('Usr');
}catch (Exception $e){
echo $e->getMessage();
}
//var_dump($user);
}
I have a database class dbconnect.php, and processform.php. Inside dbconnect.php there is a method for connecting to the database.
If there's an error, how do I throw an exception? Where do I put the try catch block, in the processform.php? People say I shouldn't echo an error directly from inside the class. Here's an example:
<?php
// dbconnect.php
class DbConnect
{
public function open_connection()
{
/* Should I do it like this? */
$this->conn = PDO($dsn, $this->username, $this->password);
if (!$this->conn) {
throw new Exception('Error connecting to the database.');
}
/* Or like this */
try {
$this->conn = PDO($dsn, $this->username, $this->password);
} catch (PDOException $e) {
echo 'Error: ', $e->getMessage(), '<br>';
}
}
?>
// processform.php
<?php
require_once 'dbconnect.php';
$pdo = new DbConnect($host, $username, $password);
try {
$pdo->open_connection();
} catch (PDOException $e) {
echo 'Error connecting to the database.');
}
?>
I really want to learn the correct way of implementing the try catch in my code.
You don't have to throw an exception manually, especially on a successful connect :-)
Instead you need to tell PDO that it needs to throw exceptions when something goes wrong and you can do that when you open your database connection:
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->conn = new PDO($dsn, $this->username, $this->password, $options);
Now you can put everything in try / catch blocks but that is not even necessary; if you don't do that, php will show you unhandled exceptions complete with a stack trace when you don't catch them manually.
And when you decide you want to fine-tune your error handling for your visitors, you can set your own exception handler using set_exception_handler(). That way you can handle everything at one place instead of wrapping different sections in try / catch blocks. Should you prefer that of course.
In my practice, I prefer to catch exception in bottom. I mean, second way in your DbConnect.
You can output error message to error log. And return an error code to front-end. So the front-end knows how to tell users an error occours in a friendly way.
What's more, you can use global error handler such as set_error_handler/set_exception_handler to do this. Redirect to an error page when error occours.
i have the following code and i'm wondering if i can use try & catch as below:
class fun_database implements idbInfo{
private $srvr=idbInfo::srvr_name;
private $usr=idbInfo::usrnm;
private $pass=idbInfo::psswrd;
private $db=idbInfo::db_name;
public function connct(){
$hookup = new mysqli($this->srvr, $this->usr, $this->pass, $this->db);
if ($hookup->connect_errno)
{
throw new Exception("Error Processing Request", 1);
}
}
public function sql_require_all($table_name, $table_col){
$hookup = new connct();
$result = $hookup->query("SELECT $table_col FROM $table_name");
if($hookup->error()){
throw new Exception("Error Processing Request", 1);
}
return $result->num_rows;
}
}
This is a simple connection to the mysql and performing some querying there. Here is and the actual call of the functions above:
$conn = new fun_database();
try{
$result = $conn->sql_require_all('wordtypes', 'types');
}
catch(Exception $err){
echo "Problems at:". $err->getMessage();
}
return "<option>".$result."</option>";
What i'm asking is a bit theory. Most probably this code is NOT WORKING (i didn't test it yet). I just want to know is it possible with one 'try' to 'catch' two exceptions (as you can see the first 'throw' is in the second method of fun_database, and the second 'throw' is in the first method of the same object which is only called from the second method).
sorry for making it too complicated but still can't figure it out id this structure of try/catch is working.
you can only catch different types of exception...
class fun_database implements idbInfo{
private $srvr=idbInfo::srvr_name;
private $usr=idbInfo::usrnm;
private $pass=idbInfo::psswrd;
private $db=idbInfo::db_name;
public function connct(){
$hookup = new mysqli($this->srvr, $this->usr, $this->pass, $this->db);
if ($hookup->connect_errno)
{
throw new DomainException("Error Processing Request", 1);
}
}
public function sql_require_all($table_name, $table_col){
$hookup = new connct();
$result = $hookup->query("SELECT $table_col FROM $table_name");
if($hookup->error()){
throw new Exception("Error Processing Request", 1);
}
return $result->num_rows;
}
}
Then:
try{
$conn = new fun_database();
$result = $conn->sql_require_all('wordtypes', 'types');
}
catch(DomainException $err){
echo "This Problem at:". $err->getMessage();
}
catch(Exception $err){
echo "That Problem at:". $err->getMessage();
}
return "<option>".$result."</option>";
you would need your class instantiation inside that try block though I believe.
It wouldn't catch the two exceptions because as soon as the first exception is thrown, it goes straight to the catch block, thereby skipping the second exception directly.
You could wrap each code which may throw an exception in its own try-catch block.
Yes and no. Your code is able to catch two of this exceptions but not both of them at the same time. When one of exception will be thrown, program execution will look for closest catch block, which fits to catch Exception class. Rest of code will be omitted.
You can throw an exception at an point in the program (not after an excpetion if it is not caught).
As soon as it hits this point it will stop and try to make the fallback to the a try catch block. As soon as it finds one it will do this block (if it is a good catch)
You could make a try catch around your entire program or just a function.
You can throw different classes of exceptions:
class ConnectException extends Exception {}
class QueryException extends Exception {}
and then catch different exceptions:
try {
// something
}
catch (ConnectException $ex) {
// connect exception
}
catch (QueryException $ex) {
// query exception
}
It is not possible because when you throw
throw new Exception("Error Processing Request", 1);
this exception it will be caught in this line
catch(Exception $err){
echo "This Problem at:". $err->getMessage();
}
you will not reach the line that can throw the other exception if first exception was thrown
I am creating a model for a small PHP application. This will utilize PDO to communicate with a MySQL-server. I have understood that the recommended error mode is the one which throws exceptions, as this allows for graceful error handling. But I don't understand how I should handle these exceptions?
Technically, it is easy, but let me give you an example:
class Model()
{
private $host = "localhost",
$user = "",
$pass = "",
$DBH;
function __construct()
{
try
{
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $e)
{
error_log($e->getMessage());
}
}
}
If I create an object Model in my controller, and it fails, I have no way of handling this in my controller, right? Or what happens when I create that object, "new Model" returns false?
Excuse me for being a newbie, but I want to be able to handle any exceptions also from other functions in the model. How should I go about this? I need to be able to know if something went wrong in my controller and be able to do the appropriate thing there.
If you want your controller to catch the exception as well, you can always rethrow it after logging.
class Model()
{
...
function __construct()
{
try
{
...
}
catch(PDOException $e)
{
error_log($e->getMessage());
throw $e;
}
}
}
Depends entirely on what the error_log function does.
You can return the exception.
You can simply die after logging the error (presumably if your application can't hit the DB then theres no graceful recovery).
You can return a custom exception via throw();
It's really just your preference.