guzzle / psr7

PSR-7 HTTP message library

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Throw a dedicated exception, not InvalidArgumentException, for malformed URIs

Daimona opened this issue · comments

Description
If I have a malformed URL (e.g. user input) and pass it to Uri::__construct, it will throw an InvalidArgumentException. As such, I believe that the only way to detect an invalid URL (and e.g. show a custom error in my application) is to catch this exception, which is not ideal: being a generic exception, such a catch clause has a concrete risk of catching an unwanted exception. This is particularly true if there are several calls between the app code and Uri::__construct. As a case in point, I have an application which uses the guzzle client like this:

// `$this->client` is a GuzzleHttp\ClientInterface, $url might be invalid
$this->client->get( $url )->getBody()->getContents();

And from here, Uri::__construct is 7 levels down in the call stack.

My proposal is that a dedicated exception be thrown instead, e.g. MalformedURIException.

Example

With a dedicated exception, the following code would be fine:

try {
   $this->client->get( $url )->getBody()->getContents();
} catch ( MalformedURIException $_ ) {
   echo "Oh noes."
}

or even just the simplified version:

try {
   $uriObj = new Uri( $url );
} catch ( MalformedURIException $_ ) {
   echo "Oh noes."
}

Additional context

I think one important thing to keep in mind is that this might be an important compatibility break. I don't have data, but I bet that code catching the InvalidArgumentException exists in the wild, so the release notes should probably mention this change. One way to reduce (eliminate?) the disruption is to have the new exception extend InvalidArgumentException.

Thank you for this issue.

Feel free to send a PR with this new exception. Just make sure it extends the InvalidArgumentExcdption to avoid a BC break.