chimit's avatar

How to catch exception from an external package?

Hi! I'm new to Lumen and Laravel. I use firebase/php-jwt package for my project. In controllers it's clear:

\JWT::decode(...)

But I can't handle exceptions from this package. I tried to do something like this: /app/Exceptions/Handler.php

public function render($request, Exception $e)
{
    if ($e instanceof DomainException) {
        return 'Caught!';
    }

    return parent::render($request, $e);
}

How can I handle exceptions from 3rd party packages? Thanks in advance!

0 likes
4 replies
toniperic's avatar

If 3rd-party package throws a custom exception, then you can catch it in a way you just described.

If it's not throwing a custom exception but rather a generic Exception, then there's no way.

1 like
chimit's avatar

Should I specify namespaces in the above example?

My task is to check JWT signature (using firebase/php-jwt package). And if signature is wrong, I want to return JSON instead of Lumen's error page. So are there any other ways to do this?

toniperic's avatar

Never used that package, so not sure whether it provides such method. I suppose it does, so check the API.

chimit's avatar
chimit
OP
Best Answer
Level 7

My problem was in backslash :)

This works good:

public function render($request, Exception $e)
{
    if ($e instanceof \DomainException) {
        return 'Caught!';
    }

    return parent::render($request, $e);
}

toniperic, thank you for your reply!

Please or to participate in this conversation.