I've been searching for a way to use a string instead of an integer for the code of a custom exception, but much to my surprise this seems impossible to do!
I'd like to be able to throw such an exception:
throw new CustomException( "user_not_found", "User not found" );
so then I can test it as follows with PHPUnit:
$this->expectExceptionCode( "user_not_found" );
$User = new User(100); // 100 is a valid id for a non-existing user
$User->delete_user(); // This method throws the above CustomException
What I've been doing so far is passing a custom context array to the exception:
throw new CustomException( "User not found", [ "debug" => "user_not_found" ] );
and then my test looks like this:
try {
$User = new User(100);
$User->delete_user();
} catch( \Throwable $e ) {
$this->assertEquals( "user_not_found", $e->getContext()["debug"] );
}
But I would really prefer the first solution because it looks cleaner to me.
Exception
, you can add whatever custom fields you want, including in the constructor. If you want to use the numeric code, you can do that with class constants, and you can use subclasses to hide these from callers, so UserNotFound automatically calls the parent with 1001 or whatever. Or, ignore the codes and inspect on the specific exception by type