How to handle error situations more elegantly in PHP?

Suppose now there is a function getUserInfo() that queries for user information and the parameter is userId. If the userId passed in does not meet the formatting requirements, or if the corresponding user information cannot be found based on this userId, the function has 2 ways to handle the situation

  • return false or null to the caller
  • Throw an exception

Which of these two methods is better and why? Is there a better way to handle errors?

A: You should choose to throw an exception, as there is too much ambiguity in using a false or null return.

For example, if you get the user information successfully, you return an array, but there is an error in the middle, so you return a false or null. If you do not make a judgement, but directly foreach the returned information or use the array_* method, you will cause an unknown exception to the caller, so in addition to throwing an exception, you should also strictly limit the input and output values to make the caller less confused.

function getUserInfo(int $id) : array;
function getUserInfo(int $id) : UserInfo;

Addendum: Exceptions can be used to return incorrect business logic to solve a deeper problem, as business processes are now often wrapped in multiple layers, and if you use values such as false, null, void, you need to make layers of judgement, leading to bloated code. Exceptions, on the other hand, can be optionally caught to terminate the business, etc.