r/PHP • • Sep 08 '20

Article Performance impact of PHP Exceptions

https://php.watch/articles/php-exception-performance
34 Upvotes

44 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Sep 09 '20

[deleted] — view deleted comment

1

u/GMaestrolo Sep 09 '20

The endpoint can throw an exception. The validator should not. The validator is concerned with "is this string empty", or "does this look like an email address". The answer to those questions is a true/false. The endpoint can see that false, and decide within its context if a false is exceptional or not. The validator doesn't know the context of the program, it only knows its one job - take input, and return true/false if it matches the expected pattern or not.

The only situation where I could see it being appropriate for a validator to throw an exception is if the validation requires interaction with an external system (e.g. the database, to check for uniqueness). Because the database is potentially volatile, it may throw an exception, and the validator may catch it if only to add more context before re-throwing it, or it may just let the exception bubble up. Either way, that exception would exist because the validator could not perform its job if comparing input to expectations, and you could argue that the validator still isn't technically throwing the exception if it's just bubbling up.

By making the validator throw exceptions, you're forcing extra handling logic into the controller, which genuinely only wants to know if validations pass or fail

1

u/colshrapnel Sep 09 '20

I make it there are two approaches. One is when your backend performs the user-friendly validation and another when everything is handled by the frontend. In the latter case indeed to throw a generic 400 Bad request would be enough.