webmozarts / assert

Assertions to validate method input/output with nice error messages.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: custom Exception

CvekCoding opened this issue · comments

What do you think about the feature to pass custom exception class, to be able to not invoke InvalidArgument always.
This can be done on config level or/and as an optional argument to assertion.

WDYT?

You can override the reportInvalidArgument method by extending the Assert class.
Here you can throw your own exception.

https://github.com/webmozart/assert/blob/255fb9e7f8bdd7a8dc8fc462ae8e8b40ce7924ad/src/Assert.php#L1200

@BackEndTea this way I have to rewrite all the code where I already use Assert:: to start using my custom version. This is not what I would like to do:).

That is correct, however the only change you would have to make would be to change the use at the top of the file, to import your own version, where you define your custom exception throwing.

Why weren't a custom exception used in place of InvalidArgumentException? Having InvalidArgumentException to be thrown all the time leads us to catch it and convert it to other exception types because assertions are not always testing arguments but for example results of method calls, etc. This creates a collision with real InvalidArgument exceptions used by other libraries or in our own code.

You can override the reportInvalidArgument method by extending the Assert class.

Overriding a method reportInvalidArgument so it does not throw InvalidArgumentException looks fishy. Plus, even if you do that, all assert methods still have signatures with '@throws InvalidArgumentException' and psalm goes crazy about it.