Mam taki problemik...próbuje się nauczyć dobrze obsługiwać błędy przy wykorzystaniu klasy exception. Zacząłem od stworzenia własnej klasy
Kod
<?php
class contentException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code);
}
// custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
?>
class contentException extends Exception
{
// Redefine the exception so message isn't optional
public function __construct($message, $code = 0) {
// some code
// make sure everything is assigned properly
parent::__construct($message, $code);
}
// custom string representation of object
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
?>
teraz mam taki kawałek kodu (fragment klasy addContent):
Kod
function setContent($content) {
if(!is_string($content) || strlen($content) == 0) {
throw new contentException('Niepoprawna treść!');
} else {
echo $content;
$this->_content = $content;
}
}
if(!is_string($content) || strlen($content) == 0) {
throw new contentException('Niepoprawna treść!');
} else {
echo $content;
$this->_content = $content;
}
}
I teraz mój problem polega na tym.
Jeżeli zrobie tak (w pliku test.php gdzie testuję powyższą klasę):
Kod
$content->setContent('');
to owszem wyświetli mi komunikat "niepoprawna treść" ale wyskoczy to jako fatal error wraz z ścieżką do pliku chyba że dam to w bloki try i catch. Jednakże dla mnie to się mija z celem bo musiałbym każdą metodę dawać w te bloki. Więcej czasu zajęło by mi pisanie samych try catch niż tworzenie aplikacji :/ czy można jakoś wymusić żeby kod który zrobiłem generował wyjątki tak jak należy bez okładania każdej metody blokami try i catch ?