PHP

PHP

Made by DeepSource

Exception being raised is not from a valid exception class PHP-E1001

Bug risk
Critical

The Exception class you are trying to use seems to be invalid. This will result in a run time fatal error.

This issue can be raised for any of the following cases:

  • Exception class does not exist.
  • Exception class exists, but does not extend PHP's in-built Exception class.

Bad practice

class NotFoundException
{
    public function __construct($message, $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    public function __toString()
    {
        return __CLASS__ . ": [{$this->code}]: {$this->message}
";
    }
}

try {
    throw new NotFoundException('Something went wrong!'); // not an exception because it do not extend `Exception` class
} catch (NotFoundException $e) {
    echo "Caught Exception
", $e;
}

try {
    throw new ForbiddenException('Forbidden!'); // exception class doesn't exist
} catch (ForbiddenException $e) {
    echo "Caught Exception
", $e;
}

Recommended

class ForbiddenException extends Exception
{
    public function __construct($message, $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    public function __toString()
    {
        return __CLASS__ . ": [{$this->code}]: {$this->message}
";
    }
}

try {
    throw new ForbiddenException('Forbidden!');
} catch (ForbiddenException $e) {
    echo "Caught Exception
", $e;
}

References