Skip to content

Commit

Permalink
Merge pull request #90 from hostep/extra-error-handling-for-DnsGetRec…
Browse files Browse the repository at this point in the history
…ord-handler

Improved handling of errors when dns_get_record function fails.
  • Loading branch information
freekmurze authored Mar 24, 2022
2 parents 1293dc4 + f886dc2 commit cdddc27
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
9 changes: 9 additions & 0 deletions src/Exceptions/CouldNotFetchDns.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,13 @@ public static function digReturnedWithError(Process $process): self

return new static("Dig command failed with message: `{$output}`");
}

public static function dnsGetRecordReturnedWithError(string $error): self
{
if ($error === '') {
$error = 'dns_get_record function failed';
}

return new static($error);
}
}
15 changes: 14 additions & 1 deletion src/Handlers/DnsGetRecord.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,24 @@

namespace Spatie\Dns\Handlers;

use Spatie\Dns\Exceptions\CouldNotFetchDns;

class DnsGetRecord extends Handler
{
public function __invoke(string $domain, int $flag, string $type): array
{
$records = dns_get_record($domain, $flag);
$records = false;
$error = '';

try {
$records = dns_get_record($domain, $flag);
} catch (\Throwable $ex) {
$error = $ex->getMessage();
}

if ($records === false) {
throw CouldNotFetchDns::dnsGetRecordReturnedWithError($error);
}

return $this->transform($type, $records);
}
Expand Down
14 changes: 14 additions & 0 deletions tests/DnsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@
use Spatie\Dns\Dns;
use Spatie\Dns\Exceptions\CouldNotFetchDns;
use Spatie\Dns\Exceptions\InvalidArgument;
use Spatie\Dns\Handlers\DnsGetRecord;
use Spatie\Dns\Records\A;
use Spatie\Dns\Records\MX;
use Spatie\Dns\Records\NS;
use Spatie\Dns\Records\Record;
use Spatie\Dns\Records\SOA;
use Spatie\Dns\Support\Collection;
use Spatie\Dns\Support\Factory;
use Spatie\Dns\Test\TestClasses\CustomHandler;

class DnsTest extends TestCase
Expand Down Expand Up @@ -150,6 +152,18 @@ public function it_throws_exception_on_failed_to_fetch_dns_record()
->getRecords('spatie.be', DNS_A);
}

/** @test */
public function it_throws_exception_on_failed_to_fetch_dns_record_with_dns_get_record_function()
{
$this->expectException(CouldNotFetchDns::class);
$this->expectExceptionMessage('dns_get_record(): A temporary server error occurred.');

$this->dns
->useHandlers([new DnsGetRecord(new Factory())])
->useNameserver('dns.spatie.be')
->getRecords('non-existing-domain.whatever', DNS_NS);
}

/** @test */
public function it_can_use_custom_handlers()
{
Expand Down

0 comments on commit cdddc27

Please sign in to comment.