From 2af6f9b6cf8ee02ec14769de1de9a245ff3edc34 Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Wed, 3 Feb 2021 19:46:49 -0800 Subject: [PATCH] APIv4 - AJAX errors should say *something* useful When calling APIv4 via AJAX, you may sometimes encounter an error. What response do you get? Before ------ You are likely to get a completely blank response (`status=500, body=[]`). There is no information in any of the logs (Apache, PHP, CiviCRM, etc). You have no way to tell what's gone wrong. Of course, if you're logged in as a full administrator, then you may have permission `view debug output`, in which case there might be something useful. But this won't help if you're using a less privileged user. After ----- For the administrator (`view debug output`), you still get a detailed error response. For less privileged users, the error is logged. The response provides a generic message along with an "Error ID". You can use the "Error ID" to locate information in the log. Also, if the error is an `UnauthorizedException`, then the response code will be a semantic 403 instead of a generic 500. --- CRM/Api4/Page/AJAX.php | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/CRM/Api4/Page/AJAX.php b/CRM/Api4/Page/AJAX.php index 2e6854f9b0..58400510f7 100644 --- a/CRM/Api4/Page/AJAX.php +++ b/CRM/Api4/Page/AJAX.php @@ -81,7 +81,10 @@ class CRM_Api4_Page_AJAX extends CRM_Core_Page { } } catch (Exception $e) { - http_response_code(500); + $statusMap = [ + \Civi\API\Exception\UnauthorizedException::class => 403, + ]; + http_response_code($statusMap[get_class($e) ?? 500]); $response = []; if (CRM_Core_Permission::check('view debug output')) { $response['error_code'] = $e->getCode(); @@ -101,6 +104,17 @@ class CRM_Api4_Page_AJAX extends CRM_Core_Page { } } } + else { + $error_id = rtrim(chunk_split(CRM_Utils_String::createRandom(12, CRM_Utils_String::ALPHANUMERIC), 4, '-'), '-'); + $response['error_code'] = '1'; + $response['error_message'] = ts('Sorry an error occurred and your request was not completed. (Error ID: %1)', [ + 1 => $error_id, + ]); + \Civi::log()->debug('AJAX Error ({error_id}): failed with exception', [ + 'error_id' => $error_id, + 'exception' => $e, + ]); + } } CRM_Utils_System::setHttpHeader('Content-Type', 'application/json'); echo json_encode($response); -- 2.25.1