Article From:https://segmentfault.com/q/1010000011706053
Question:

I now return values with [code = 200,’type’= false]. Is there a way to detect and return them directly using exception handling?

Answer 0:

Write an exception class that inherits the PHP exception, throw it as you handle it, pass your code and type or whatever else you need in the constructor.

use Exception;

abstract class BaseException extends Exception {

    /**
     * @var string
     */
    protected $status;

    /**
     * @var array
     */
    protected $data;

    /**
     * BaseException constructor.
     * @param string $message
     * @param int $code
     */
    public function __construct($message = '', $code = 0) {
        parent::__construct($message, $code);
    }

Business needs a variety of exceptions to inherit a basic exception.

class ApiException extends BaseException {
    public function __construct()
    {
        parent::__construct($data['errmsg'],$data['errcode']);
    }
}

When the business needs to be lost

    if (!$hasAction) {
        throw new ApiException(998, 'No access rights);}

Business needs to be grasped.

    try {
        //business} catch (ApiException $exception) {}

Leave a Reply

Your email address will not be published. Required fields are marked *