Answer the question
In order to leave comments, you need to log in
What is the right way to throw an exception?
We have an Address class with a constructor
public function __construct(string $country,string $city, string $street, string $house, string $building = '') {}
private function isCountryValid($param) {
if (empty($param) || !preg_match("/^[а-яё0-9- ]+$/iu", $param)) {
throw new AddressWithoutCountryException($param);
}
}
public function testAddressCreatedWithoutCountry() {
$this->expectException(AddressWithoutCountryException::class);
CreateCompanyBuilder::instance()->withAddress(new Address('', 'Москва', 'Солнечная', '15',''))->build();
}
public function testCreateCompanyWithoutAddress() {
$this->expectException(CompanycWithoutAddressException::class);
CreateCompanyBuilder::instance()->withAddress(new Address())->build();
}
Failed asserting that exception of type "ArgumentCountError" matches expected exception ... at least 4 expected
ArgumentCountError
, (and where) to throw an exception likeclass CompanyWithoutAddressException extends ArgumentCountError {
public function __construct()
{
parent::__construct('У организации должен быть заполнен адрес');
}
public function __construct(string $country,string $city, string $street, string $house, string $building = '0') {
if (!$country && !$city && !$street && !$house) {
throw new CompanyWithoutAddressException();
}
string $country,string $city, string $street, string $house, string $building = ''
with optional parameter $building (building). It may or may not be. You can remove it from the constructor and pass it as a setter, but I would like to put the entire dto directly into the constructor.
Answer the question
In order to leave comments, you need to log in
Make all parameters optional (or pass them as a single array or via setters), check the passed and throw the necessary exceptions.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question