Error Handling with Hooks

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mliebherr99
    Junior Member
    • Oct 2021
    • 7

    Error Handling with Hooks

    Hello,

    i am using afterSave() with https://docs.espocrm.com/development/hooks/ and wonder how i can do the error handling.

    In afterSave() i call an api to other systems, and those sometimes return errors.
    How can i passt those errors to the Espo GUI?
    Right now i only get a red box with "bad server response".

    Cheers,
    Michael
  • yuri
    Member
    • Mar 2014
    • 8440

    #2
    Hi Michael,

    In the back-end you need to throw the Conflict exception

    PHP Code:
    $body = json_encode($someData);
    
    throw \Espo\Core\Exceptions\Conflict::createWithBody('myConflictReason', $body); 
    

    In metadata: custom/Espo/Resources/metadata/clientDefs/{EntityType}.json:

    Code:
    {
        "saveErrorHandlers": {
            "myConflictReason": "custom:my-conflict-handler"
        }
    }

    Create a file client/custom/src/my-conflict-handler.js:

    Code:
    define('custom:my-conflict-handler', [], function () {
        return class {
    
            constructor(recordView) {
                this.recordView = recordView;
            }
    
            process(responseData) {
    
            }
        }
    );
    Clear cache.
    If you find EspoCRM good, we would greatly appreciate if you could give the project a star on GitHub. We believe our work truly deserves more recognition. Thanks.

    Comment

    • alter
      Member
      • Apr 2018
      • 57

      #3
      Hi Michael, alternative way how to show error is simply via try/catch logic - just place the important parts of the code (e. g. call to another service etc.) to try and then catch exception:

      PHP Code:
      protected function afterSave()
      {
      $testData = [];
      
      try
      {
      $myService->submitData($testData);
      }
      catch (Exception $error)
      {
      throw new Exception($error);
      }
      } 
      
      This will show the whole Exception body in that red line in the GUI - but that could be a really long text, so I would recommend to retrieve just the message from the Exception.

      I also use the "throw new Exception()" in the case where I want to restrict the users certain actions - this logic kills the transaction, that means:

      PHP Code:
      if ($myVariable === null)
      {
      throw new Exception('The variable cannot be null.');
      }
      
      $anotherVariable = $myVariable; // this code will never execute if $myVariable will be null - it will execute only if $myVariable has some kind of value. 
      

      Comment

      Working...