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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Releated

Why does nginx reverse Proxy have poor concurrency performance?

Problem description: The hardware configuration of the front-end server and the source server is as follows. The system is centos7: CPU: E5-2696V4*2(88 threads)Memory: 64GB DDR4Hard disk: 500GB SSD (about 450M/s for read/write) Both the front-end and back-end servers use nginx, and they can test concurrency independently. After the front-end reverse proxy connects to the back-end, […]