Pages

Thursday, June 27, 2019

SugarCRM: Exceptions

A number of years ago I read a funny comment about computers which read as follows:

"The problem with computers is that they do what you tell them to do, not what you want them to do."

The point being that computers do not think, they just follow instructions. As such, programmers have to be mindful of the instructions given and anticipate problems. While it is not possible to account for every possible scenario that may generate a problem, we do want to accommodate common scenarios and capture problems as exceptions, allowing our code to fail gracefully and providing feedback to the user in the form of an error message.

Within the Sugar framework, it is possible to easily implement such exceptions and provide feedback to the user.

An exception class, named SugarApiException, is provided out-of-box and can be implemented into your PHP customizations as illustrated by the following pseudo-code:



For the above example, the Sugar API would return a response code of 422, with the body of the error message being the string defined in the code (i.e. 'You are missing a parameter required for properly invoking this endpoint.').

Of course, this would be more useful if we had a selection of response codes and errors. The list of available options is defined within the previously mentioned SugarApiException class, found in the following file:

./include/api/SugarApiException.php

Here is the definition for the example used in the pseudo-code, where you will see the response code and error title:

/**
 * One of the required parameters for the request is missing.
 */
class SugarApiExceptionMissingParameter extends SugarApiException
{
    public $httpCode = 422;
    public $errorLabel = 'missing_parameter';
    public $messageLabel = 'EXCEPTION_MISSING_PARAMTER';
}

Hopefully this will help save you time implementing a process for handling errors!