psalm: False positive on Exception::getCode

Only PDOException can return a string error code, everything else will return int.

https://www.php.net/manual/en/class.pdoexception.php

PDOException extends RuntimeException {
    /* Properties */
    public array errorInfo;
    protected string code;
    
    /* Inherited properties */
    protected string message;
    protected int code;

https://www.php.net/manual/en/class.exception.php

Exception implements Throwable {
    /* Properties */
    protected string message ;
    protected int code ;

Code to reproduce https://psalm.dev/r/e785986fc0

Expected result No Error. Psalm should distinguish PDOException from others.

Related commit: 53cd878694d680fb32be4a8d5be35c8eb21c2c64

Note: How to solve this conflict? https://psalm.dev/r/b44df0b0e1

Another side effect: https://3v4l.org/Ya32I

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 2
  • Comments: 26 (6 by maintainers)

Most upvoted comments

This issue is more important now because phpstan infer the getCode return type since https://github.com/phpstan/phpstan-src/commit/e04cc8dfb8f6b3a2c4ac399232a6691baed1d162

Which means that if you cast to int to please psalm, you ends with a phpstan error “useless cast”, but if you don’t do it, you ends with a psalm error about int|string.

You can see here https://phpstan.org/r/1192e2bc-3506-41e8-ab1d-08c4faf77961 that PHPStan consider that \Exception and \Throwable can return int|string but extending them is restricting the type to int \PDOException and extensions are returning string Everything else is returning int.

What would be the easiest way to introduce this behavior to psalm @orklah ?