Json Error Reporter
Builds a standardized JSON error payload without exposing internals.
Function signature
ogBuildJsonErrorResponse(error_code, public_message, field_errors = array())
Categories
- APIs and Webhooks
Parameters
error_codeStable public error code.public_messageSafe message for the browser or API consumer.field_errorsField-level errors safe for display.Return value
Short public-safe status message.
- error
- message
- fields
Compatibility
Existing function name and call order preserved; metadata signature corrected to source.
Minimum PHP version: 7.4
Security notes
Validate request method, identity, permissions, and caller-owned allowlists before use; keep secrets and internal paths out of public output.
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Builds a standardized JSON error payload without exposing internals.
*
* Primary use case: AJAX/API validation failures.
* Typical inputs: error code, public message, field errors.
* Typical output: JSON error array.
*
* Implementation note: Separate public message from logged technical details.
*
* @param string $error_code Stable public error code.
* @param string $public_message Safe message for the browser or API consumer.
* @param array $field_errors Field-level errors safe for display.
* @return array Structured JSON error payload.
*/
function ogBuildJsonErrorResponse($error_code, $public_message, $field_errors = array()) {
$result = array(
'success' => false,
'message' => '',
'data' => array()
);
$error_code = trim((string)$error_code);
$public_message = trim((string)$public_message);
if (empty($error_code)) {
$error_code = 'error';
}
if (empty($public_message)) {
$public_message = 'The request could not be completed.';
}
if (!is_array($field_errors)) {
$field_errors = array();
}
$clean_fields = array();
foreach ($field_errors as $field => $message) {
$field = preg_replace('/[^a-z0-9_\-]/i', '', (string)$field);
if (!empty($field)) {
$clean_fields[$field] = (string)$message;
}
}
$payload = array(
'success' => false,
'error_code' => $error_code,
'message' => $public_message,
'field_errors' => $clean_fields
);
$result['success'] = true;
$result['message'] = 'JSON error response built.';
$result['data'] = $payload;
return $result;
}