When programming PHP Socket, the error handling mechanism is an important part of ensuring the robustness of the program. PHP provides two core functions: socket_clear_error() and socket_last_error() to help developers obtain and handle Socket errors. However, the output of these two functions themselves is still relatively low-level, and there are still some inconveniences for developers to quickly locate and solve problems. This article will explore how to combine these two functions with a custom error code mapping mechanism to build a more efficient and practical error handling solution.
This function returns the error code of the most recent Socket operation. You can obtain the last Socket error code without passing in the parameters, or you can pass in a specific Socket resource to obtain the corresponding errors for the resource.
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, 'm66.net', 80);
$errCode = socket_last_error($socket);
echo "Error code:$errCode\n";
Get text description of the error code:
echo socket_strerror($errCode);
This function can clear the current or specified Socket error status to avoid the old error code affecting the judgment of a new round of operations.
socket_clear_error($socket);
Although socket_strerror() provides error description information, its information is generally more general and mostly in English, and is often not clear enough for complex scenarios (such as multilingual output, error level classification, development and debugging vs production logs). Therefore, introducing a set of "custom error code mapping mechanism" is the key to improving the quality of error processing.
We can map common error codes through an associative array. Examples are as follows:
$socketErrorMap = [
10061 => ['msg' => 'Connection refused,The target host has no listening service', 'level' => 'error'],
10060 => ['msg' => 'Connection timeout,The server is not responding', 'level' => 'warning'],
10054 => ['msg' => 'The remote host forced an existing connection to close', 'level' => 'error'],
// Add more maps...
];
function handleSocketError($socket = null, $clear = true) {
$errCode = socket_last_error($socket);
global $socketErrorMap;
$defaultMsg = socket_strerror($errCode);
$mapped = $socketErrorMap[$errCode] ?? ['msg' => $defaultMsg, 'level' => 'notice'];
if ($clear) {
socket_clear_error($socket);
}
// Extended to logging、Exception thrown, etc.
echo "[{$mapped['level']}] Error code: $errCode - {$mapped['msg']}\n";
}
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
@socket_connect($socket, 'm66.net', 12345); // Assume that this port has no monitor
handleSocketError($socket); // Output more friendly error message
socket_close($socket);
The output may be:
[error] Error code: 10061 - Connection refused,The target host has no listening service
Separation of development environment and production environment : detailed error information can be output during the development stage, and the production environment can be unified into a standard log format.
Use in combination with logging systems : You can use log libraries such as Monolog to record error information to files, databases or monitoring systems.
Adaptable multilingual support : error description information can be expanded into multilingual formats, improving the internationalization capabilities of the system.
Through socket_clear_error() and socket_last_error() combined with custom error mapping mechanisms, we can achieve more refined error recognition and response, greatly improving the maintainability and user-friendliness of Socket applications. This approach not only enhances the readability of error semantics, but also lays the foundation for subsequent extensions (such as automatic retry, fine-tuned logging, etc.). This is a best practice worth promoting for developers.