Php error handling classes

Error Handling in a PHP Class

What’s the best practice to handle errors if using objects? A) Before the method of object is called and not even getting to execute method if there’s some error, or B) Just pass parameters and perform error checking in method itself, returning error code or something. Solution 2: To choose from options you offer it would be B, but don’t use error codes and throw exceptions instead.

Error Handling in a PHP Class

Hey there, here is a question for you guys.

I have so much times to choose a error handling for classes in PHP.

For Example in Ajax PHP Handling Classes i do it this way:

public function setError($msg) < $this->errors[] = $msg; > public function isFailed() < return (count($errors) >0 ? true : false); // if errors > 0 the request is failed > public function getJsonResp() < if($this->isFailed()) < $resp = array('result' =>false, 'message' => $this->errors[0]); > else < $resp = array('result' =>true); array_merge($resp, $this->success_data); // the success data is set later > return json_encode($resp); > // an example function for a execution of a method would be this public function switchMethod($method) < switch($method) < case 'create': if(!isset($param1, $param2)) < $this->setError('param1 or param2 not found'); > else < $this->createSomething(); > break; default: $this->setError('Method not found'); > > 

So lets know you what i want to aks for: Is there a better solution for error handling?

When it comes to OOP Your best bet is to use Exceptions to handle your errors, for example:

class Example extends BaseExample implements IExample < public function getExamples() < if($this->ExamplesReady === false) < throw new ExampleException("Examples are not ready."); >> > class ExampleException extends Exception<> 

throwing exceptions within your class and catching exceptions outside of the classes that throw them is the way I usually go about things.

$Example = new Example(); try < $Examples = $Example->getExamples(); foreach($Examples as $Example) < //. >>catch(ExampleException $e) < Registry::get("Output")->displayError("Unable to perform action",$e); > 

and your displayError would use $e->getMessage() as the information regarding the error.

Читайте также:  Не получается открыть файл html

Generally when programming in OOP, you will make heavy use of Exceptions as your «error» handler.

Creating a error handler class in php, set_exception_handler();. in a class to set up a error handling class in php, that when ever an error is thrown is handled by this class. As

Learn Object Oriented PHP Beginner to Advanced [2021]

Exceptions allow you to handle errors in a graceful, object oriented way. I demonstrate by Duration: 13:45

Exceptions & Try Catch Finally Blocks

In the first section of the course, we covered error handling, in this lesson you will learn how to Duration: 21:18

PHP Error Handling & Error Handlers

In this PHP tutorial, you will learn different types of errors in PHP as well as the basics of Duration: 7:30

Objects and error handling in PHP

What’s the best practice to handle errors if using objects?

A) Before the method of object is called and not even getting to execute method if there’s some error, or

B) Just pass parameters and perform error checking in method itself, returning error code or something.

Please pick your option and short description, why?

Thanks orlandu63, it is good practice, but what about non-fatal errors, such as user should provide a title for something, and he/she didn’t?

class Sample < var $err_no_title = 1; function createNewRecord ($title) < if (!$title) return $this->err_no_title; > > 

Or use exceptions for these kind of errors also?

If you’re using OO, you might as well use Exceptions. My answer is a mix of both A and B:

class DatabaseConnectionException extends Exception <> class Database < public function connect($user, $pass, $db) < //Connection stuff. if($baduser) < throw new DatabaseConnectionException('Username (' . $user. ') is invalid.') >if($badpass) < //'' >> > $db = new Database; try < $db->connect($user, $pass, $db); catch (DatabaseConnectionException $e)

What are the advantages to this? I don’t know, but it seems right.

You can read more on it on http://php.net/exceptions and google.

Regarding your second part,

First of all your example will treat it more of an error than a «warning» since you exit the function and thus don’t create a record if you have no title. This shows that method B is flawed. So method A all the way.

To choose from options you offer it would be B, but don’t use error codes and throw exceptions instead. All the logic (even validation of inputs) should be encapsulated in the function.

  1. The function may change and so may change requirements for inputs.
  2. User of your function may not always know, what the inputs should be like.
  3. You surely don’t want to repeat the validation code everywhere you use the function.

Be careful though, as exceptions are raised by object oriented code only. For example this code does not fire an exception:

Your example would be like:

 > . try < $mysample->createNewRecord($title); > catch ($ex) < echo "Could not create record. Please try again. (Reason: $ex)"; >. ?> 

In the first place, this sort of thing should be validated in the user interface. So it would be A, but B needs to be there to. So final verdict would be: both.

PHP Error Handling, The default error handling in PHP is very simple. An error message with filename, line number and a message describing the error is sent to the browser.

Handling errors from PHP OOP to jQuery

I’m trying to learn OOP in PHP but I’m having some troubles at the moment. Whenever method is executed i don’t know what value should i return to be able to handle it with jQuery in both cases — true and false. For example, in Pick_data() if false i want to get value like: «Fill in all fields» and most important, to be able to display it for user using jQuery or Ajax. I will leave code down below. Places commented ,,//I NEED HELP HERE» is my problem. I’m not asking you to write whole code and just need reference to information how can i deal with it. I would appreciate that because i’m completely lost. I will leave code down below(it’s working fine expect my problem). Thanks!

username = trim($_POST['username']); $this->password = trim($_POST['password']); > //end of if isset if (!empty($this->username) && !empty($this->password) ) < return true;//NEED HELP HERE >//end of is empty else //NEED HELP HERE > //end of Pick_data public function Username_equivalent_check() < $find_username_equivalent = mysql_query("SELECT * FROM websiteusers WHERE Username='".$this->username."'"); if (mysql_num_rows($find_username_equivalent) == 0) < return true;//NEED HELP HERE >//end of (mysql_num_rows) else //NEED HELP HERE > //end of Username_equivalent_check public function Input_data() < $input_user = mysql_query("INSERT INTO websiteusers (Username, Password) VALUES ('$this->username','$this->password')"); if ($input_user) < return true; //NEED HELP HERE >//end of inputing new user data else //NEED HELP HERE > //end of input_data > //end of class $var = new Registration; $var->Pick_data(); $var->Username_equivalent_check(); $var->Input_data(); ?> 

There are several ways to do this. Here are a few suggestions:

When an error occurs, you do not just want to return a true/false result, but you want to return a text message. That text message can then be displayed (or can be passed to jQuery or whatever). Since you are a beginner, I would say just change your functions to return a string value (the actual error message text) instead of returning just false in case of an error. Something like this:

public function Pick_data() < if (isset($_POST['username'])) $this->username = trim($_POST['username']); if (empty($this->username)) return 'User name must be specified.'; if (isset($_POST['password'])) $this->password = trim($_POST['password']); if (empty($this->password)) return 'Password must be specified.'; return true; > 

As you can see above, your Pick_data function will return with an error message (a string value) if either one of the required fields were empty. It will only return true if there were no errors.

Then when you call this function, you must check its return value:

$var = new Registration; $result = $var->Pick_data(); if ($result !== true) < echo 'Error: ' . $result; // This gets executed when Pick_data returned an error message >else < // This gets executed when Pick_data returned true, so only here you should continue: $result = $var->Username_equivalent_check(); // you must check here the $result variable again as it now contains the return value of your Username_equivalent_check function // . and so on > 

If you must do a lot of checks one after the other, you’ll end up with a lot of nested if / else statements. Which is not so great. But as a beginner programmer you need to learn that you should almost always need to check the return value of each(!) function you call!

A more advanced solution is to use a try / catch block, something like this:

try < $var = new Registration; $var->Pick_data(); $var->Username_equivalent_check(); $var->Input_data(); > catch(Exception $e) < // Get the error message: $error_msg = $e->getMessage(); // and print it out echo 'Error: ' . $error_msg; > 

To make the above try / catch block work, you must(!) also change your functions to throw an exception (error) when something goes wrong, something like this:

public function Pick_data() < if (isset($_POST['username'])) $this->username = trim($_POST['username']); if (empty($this->username)) throw new Exception('User name must be specified.'); if (isset($_POST['password'])) $this->password = trim($_POST['password']); if (empty($this->password)) throw new Exception('Password must be specified.'); > 

Using try / catch blocks are much more elegant because you do not end up with a lot of nested if / else statements. Note: when an exception is thrown while the program is running within a try / catch block the program execution stops there immediately and the catch block gets executed.

I think now you have a better idea on how to handle error events in PHP.

If you want to display the error message in the user’s web browser with jQuery then you must pass the error message from the server which runs your PHP code to the browser which can only run javascript (jQuery is written in javascript). Nowadays forms are being submitted from the browser to the server via an Ajax call. It looks something like this: First the form gets being displayed in the browser (PHP sends the page containing the form to the browser when the user visits your page). The user fills the form and when hitting the Submit button javascript takes over and sends the form data to the server. This way the user is still on the same page, in other words the page does not get reloaded. When your server receives the Ajax request from the javascript code running in the browser, it does the actual processing, in your example checks the values of the form fields, etc. Finally the server sends the results back usually as a JSON object to the browser, to the calling javascript program. Then the results can be displayed by the javascript code running in the user’s browser. So for what you want to do you need to learn both PHP and javascript programming and you need to learn using jQuery and the JSON format as well.

Objects and error handling in PHP, The function may change and so may change requirements for inputs. · User of your function may not always know, what the inputs should be like.

Источник

Оцените статью