开发者

Better way of error handling?

开发者 https://www.devze.com 2023-03-04 23:32 出处:网络
What are best way of error handling? This is what I came up with: class test { public static function Payment($orderid, $total) {

What are best way of error handling? This is what I came up with:

class test {

    public static function Payment($orderid, $total) {
        if (empty($orderi开发者_高级运维d) && empty($total)) {
            return array('status' => 'fail', 'error' => 'Missing Data');
        }
    }

}

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


If you use PHP 5, you can handle error with exception :

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

This way is cleaner than manual set exception message, because you have access to a try catch system and you can isolate exception handling


As mentioned, use Exceptions. Specific to your example, you throw an exception if some condition fails. Then when you envoke the method that can throw an exception, you wrap it with a try/catch handling block.

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 
}


You could use exceptions.

However, in the use case you've posted, simply doing the checks at the controller level should suffice.

I also think that explicitly checking the return type for array (on fail) is counter intuitive.


Here is how you might modify your code to use an exception. It also helps to document the circumstances under which the exception is thrown.

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 extra 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;
  }
}


I tend to lean towards throwing exceptions, and then using the try/catch mechanism to deal with the aftermath. The man page is here: http://php.net/manual/en/language.exceptions.php


The best practice is to use Exceptions.

http://php.net/manual/en/language.exceptions.php

0

精彩评论

暂无评论...
验证码 换一张
取 消