Standardizing API Response Formats and Error Handling in PHP
This guide outlines a unified JSON response structure, defines standard HTTP status codes, presents common data payload formats, provides reusable PHP functions for broadcasting messages, and demonstrates custom error handling within a WebSocket gateway to improve backend consistency and robustness.
Data Format Conventions
All API endpoints must return a unified JSON structure, even when no data is found. Both server and client must ensure the JSON is syntactically valid.
Status Code Specification
200 OK – Request succeeded.
400 Bad Request – Business error or malformed request.
401 Unauthorized – Authentication required.
403 Forbidden – No permission to invoke.
404 Not Found – No data available.
500 Internal Server Error – Server encountered an error.
Common Response Formats
Basic response
{
"code":200,
"msg":"success",
"data":{}
}Object response
{
"code":200,
"msg":"success",
"data":{
"id":10086,
"name":"Tinywan",
"age":20,
"sex":1
}
}Array response
{
"code":200,
"msg":"ok",
"data":[
{"id":1,"name":"poppy","age":20},
{"id":2,"name":"thorn","age":18}
]
}Paginated list response
{
"code":200,
"msg":"ok",
"data":{
"total":10,
"list":[
{"id":1,"name":"poppy","age":20},
{"id":2,"name":"thorn","age":18}
]
}
}File list response
{
"code":200,
"msg":"ok",
"data":[
"https://tinywan.com/file/upliad/20172514.jpg",
"https://tinywan.com/file/upliad/20172515.jpg"
]
}Unified Broadcast Function
/**
* @desc: Message broadcast JSON data
* @param int $code
* @param string $msg
* @param array $data
* @return false|string
*/
function broadcast_json(int $code = 0, string $msg = 'success', array $data = []) {
return json_encode([
'code' => $code,
'msg' => $msg,
'data' => $data
], JSON_UNESCAPED_UNICODE);
}Message Handling with Validation
/**
* @desc onMessage
* @param string $clientId
* @param string $message
* @return bool
*/
public static function onMessage(string $clientId, string $message): bool {
$originMessage = json_decode($message, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Gateway::closeClient($clientId, broadcast_json(400, 'Invalid JSON data'));
return false;
}
return Gateway::sendToClient($clientId, broadcast_json(200, 'Request successful', $originMessage));
}Custom Error Handler
/**
* Register a global error handler that converts PHP errors into ErrorException instances.
*/
public static function onWorkerStart(Worker $worker) {
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) {
return;
}
throw new \ErrorException($message, 0, $severity, $file, $line);
});
}Enhanced onMessage with Exception Handling
public static function onMessage(string $clientId, string $message): bool {
try {
$originMessage = json_decode($message, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Gateway::closeClient($clientId, broadcast_json(400, 'Invalid JSON data'));
return false;
}
// Example runtime exception (division by zero)
$aa = 1 / 0;
var_dump($aa);
} catch (\Throwable $e) {
return Gateway::sendToClient($clientId, broadcast_json(500, $e->getMessage()));
}
return Gateway::sendToClient($clientId, broadcast_json(200, 'Request successful', $originMessage));
}Reference Implementation
Complete source code is available at https://github.com/Tinywan/webman-admin
Illustrative Images
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
