Skip to content

Commit

Permalink
Merge pull request #65 from mterwill/string-error-codes
Browse files Browse the repository at this point in the history
bugfix: Ensure error code is an int
  • Loading branch information
sagikazarmark authored Jul 30, 2021
2 parents 9dceedb + 821e453 commit 7bf5510
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

- Fix TypeError when exceptions with string error codes are thrown

## [0.7.3] - 2021-06-29

Expand Down
3 changes: 2 additions & 1 deletion example/generated/Twitch/Twirp/Example/TwirpError.php

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions example/tests/TwirpErrorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,4 +102,30 @@ public function it_creates_an_error_from_an_exception_with_a_custom_message(): v
$this->assertEquals('custom msg', $error->getMessage());
$this->assertEquals('msg', $error->getMeta('cause'));
}

/**
* Exception->getCode is not guaranteed to return an int, even though the method has a type hint.
* See: https://www.php.net/manual/en/exception.getcode.php
* > Returns the exception code as int in Exception but possibly as other
* > type in Exception descendants (for example as string in PDOException).
*
* @test
*/
public function it_works_with_string_codes(): void
{
$exception = new class('msg', 'code') extends \PDOException
{
public function __construct(string $msg, string $code)
{
parent::__construct($msg);
$this->code = $code;
}
};
$error = TwirpError::errorFrom($exception);

$this->assertEquals(ErrorCode::Internal, $error->getErrorCode());
$this->assertEquals('msg', $error->getMessage());
$this->assertEquals('msg', $error->getMeta('cause'));
$this->assertEquals(0, $error->getCode());
}
}
4 changes: 3 additions & 1 deletion protoc-gen-twirp_php/templates/global/TwirpError.php.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,10 @@ final class TwirpError extends \Exception implements Error
public static function errorFrom(\Throwable $e, string $msg = ''): self
{
$msg = empty($msg) ? $e->getMessage() : $msg;
// Exception->getCode is not guaranteed to return an int, see https://www.php.net/manual/en/exception.getcode.php
$code = is_int($e->getCode()) ? $e->getCode() : 0;

$err = new self(ErrorCode::Internal, $msg, $e->getCode(), $e);
$err = new self(ErrorCode::Internal, $msg, $code, $e);
$err->setMeta('cause', $e->getMessage());

return $err;
Expand Down

0 comments on commit 7bf5510

Please sign in to comment.