Best way to handle errors?

What is the best way to handle errors? Here is what I came up with:

class test { public static function Payment($orderid, $total) { if (empty($orderid) && empty($total)) { return array('status' => 'fail', 'error' => 'Missing Data'); } } } 

I heard about Try / Exceptions, but how to fit into my code? If you could provide an example, that would be great!

+4
source share
6 answers

As already mentioned, use Exceptions . Specifically for your example, you throw exception if some condition is not met. Then, when you call a method that can throw an exception, you carry it with the try/catch processing try/catch .

 class test { public static function Payment( $orderid, $total ) { if (empty( $orderid ) && empty( $total )) { throw new Exception('Missing Data'); } } } try { test::Payment("1", "2"); //should be fine test::Payment(); //should throw exception } catch (Exception $e){ echo $e; //do other things if you need } 
+3
source

If you are using PHP 5, you can handle the error with the exception:

http://fr2.php.net/manual/en/class.exception.php

This method is cleaner than manually reporting an exception because you have access to the catch try system and you can isolate exception handling

+5
source

You can use exceptions .

However, in the case you have published, it’s easy enough to perform checks at the controller level.

I also find that explicitly checking the return type for an array (on failure) is intuitive.

+1
source

Here is how you can change your code to use an exception. It also helps to document the circumstances in which an exception occurs.

 class test { /** * [method description] * @throws Exception if the order ID or total is empty */ public static function Payment($orderid, $total) { if (empty($orderid) && empty($total)) { throw new Exception("fail: Missing Data"); } } } 

You can also create your own exception class if you want to include additional data in the exception.

 class MyException extends Exception{ public $status, $error; public function __construct($status, $error){ parent::__construct("$status: $error"); $this->status = $status; $this->error = $error; } } 
+1
source

I tend to throw exceptions and then use the try / catch mechanism to deal with the consequences. The man page here: http://php.net/manual/en/language.exceptions.php

0
source
0
source

All Articles