From abbfd70319043b59419cd34d00182f4b0e45c155 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Mon, 20 Nov 2023 18:45:50 +0100 Subject: [PATCH] Tpl: add display_ajax_error() helper method --- src/Tpl.php | 38 +++++++++++++++++++++++++++++++++----- 1 file changed, 33 insertions(+), 5 deletions(-) diff --git a/src/Tpl.php b/src/Tpl.php index c8bd4bb..89aede5 100644 --- a/src/Tpl.php +++ b/src/Tpl.php @@ -524,16 +524,21 @@ class Tpl { /** * Display AJAX return * @param array|null $data AJAX returned data (optional) + * @param int|null $error_code HTTP error code (optional, default: 400 if not $data['success']) * @param bool $pretty AJAX returned data * (optional, default: true if $_REQUEST['pretty'] is set, False otherwise) * @return never */ - public static function display_ajax_return($data=null, $pretty=false) { + public static function display_ajax_return($data=null, $error_code=null, $pretty=false) { if (!is_array($data)) $data = array(); - // Adjust HTTP error code on unsuccessfull request - elseif (isset($data['success']) && !$data['success'] && http_response_code() == 200) - http_response_code(400); + + // Adjust HTTP error code on unsuccessfull request (or if custom error code is provided) + if ( + $error_code + || (isset($data['success']) && !$data['success'] && http_response_code() == 200) + ) + http_response_code($error_code ? $error_code : 400); $data['messages'] = self :: get_messages(); if (!$data['messages']) unset($data['messages']); @@ -550,6 +555,29 @@ class Tpl { exit(); } + /** + * Display AJAX error + * @param string|null $error Error message (optional) + * @param int|null $error_code HTTP error code (optional, default: 400) + * @param bool $pretty AJAX returned data + * (optional, default: true if $_REQUEST['pretty'] is set, False otherwise) + * @return never + */ + public static function display_ajax_error($error=null, $error_code=null, $pretty=false) { + self :: display_ajax_return( + array( + 'success' => false, + 'error' => ( + $error? + $error: + I18n::_("Unexpected error occured. If problem persist, please contact support.") + ), + ), + $error_code, + $pretty + ); + } + /** * Handle a fatal error * @param string $error The error message @@ -576,7 +604,7 @@ class Tpl { // Handle API mode if (Url :: api_mode()) - self :: display_ajax_return(array('success' => false, 'error' => $error)); + self :: display_ajax_error($error); self :: assign('fatal_error', $error); self :: display('fatal_error.tpl');