No announcement yet.

How can I trap an exception in a hook?

  • Filter
  • Time
  • Show
Clear All
new posts

  • How can I trap an exception in a hook?

    public function beforeSave(Entity $targetList, array $options): void
        try {
            // this is caught & rethrown in Slim\Middleware\ErrorMiddleware
            throw new Exception('test');
        } catch (Throwable $e) {
            // this is never called
            $GLOBALS['log']->error('NEVER CAUGHT');

    I'm writing a module to interface with an external REST API (Mailchimp).
    In some cases the API may throw an exception.
    When this happens the exception is handled and passed back to the UI - my catch code is never called.
    Seems to happen in any of the hook functions.

    How should I handle this?
    (I'm actually calling the remote API in a service class called from the hook - where I get the same behavior)

  • #2
    No, unless your exception occurs within a particular hook. The hook is executed and exits.

    If your logic is executed during a record save, you can extend the repository save method.


    • #3
      My workaround requires extra API calls to avoid possible exceptions - which exacerbates another issue - the delay caused by the REST calls.

      I'm not a PHP expert - if I was in a Javascript environment the simple solution would be to run it asynchronously -

      If I set up Jobs to handle long running API conversations - it seems like I can run the job with JobRunner->run(JobEntity).
      Will that run asynchronously?

      Would I be better off using a third party lib like
      Easily run code asynchronously. Contribute to spatie/async development by creating an account on GitHub.

      Is there already a PHP lib to handle async functions in Espo?


      • rabii
        rabii commented
        Editing a comment
        AFAK spatie/async is already used within espocrm to run multiple jobs in parallel.

      • cnewell
        cnewell commented
        Editing a comment
        You're right! I searched the source but was set to case-sensitive!
        Thanks Rabii!

    • #4
      I believe there are PHP libraries which handle multiple HTTP requests problem specifically. In PHP is not that good with async by its nature.