1

Is there a way to handle all errors, from my symfony controllers, for example, if I get this error:

enter image description here

In my controller is there a way using try/catch to get this error?. For example:

class SomeClass extends Controller
{
    public function doSomethingAction(Request $request){
        //do something
        try {
            //do something
        }
        catch(\Exception $e){
            dump("ERROR:".$e->getMessage()); //<--this is not dumping anithing
        }
    }
}

I get allways the red screen message in the network call preview: enter image description here

Instead of something like:

"ERROR: Type error: Argument 1 passed to.....

1
  • 1
    You are not giving us enough input. Are you sure the //do something are what causes your exception and not a dependency injection or an erroneous ParamConverter value? Commented Mar 20, 2019 at 19:21

1 Answer 1

3

With PHP 7 you are able to handle PHP errors like TypeErrors from mismatching types (like in your example) as well as exceptions by catching their shared interface Throwable.

You should be careful with this, especially outside controllers, as this could prevent you from seeing unexpected errors which can lead to problems down the line or you not seeing when parts of your application are entirely broken. At the very least you should have proper logging in place.

In summary, you can catch errors along with exception like this:

try {
    ...
} catch (\Throwable $error) {
    ...
}
Sign up to request clarification or add additional context in comments.

6 Comments

That's what I first wondered. But FatalThrowableError extends FatalErrorException that extends \ErrorException in Symfony. And \ErrorException really is an exception and not an \Error, so the OP catch should do.
The FatalThrowableError is used by Symfony's DebugHandler to wrap php errors e.g. to uniformly deal with errors & exceptions inside the exception listener. Inside the form this should still be a regular \TypeError which means it's a \Throwable. See github.com/symfony/debug/blob/master/ErrorHandler.php#L645 (the method itself is used inside register() for \register_shutdown_function())
Right, I got fooled by the fact that we only see the beginning of the stack trace
Could worth a recommendation to catch \TypeError rather than \Throwable then, to narrow it down and not catch everything as you perfectly pointed it
Yes, that would work too and in most cases I would suggest doing that to prevent the issues, i.e. unknowingly suppressing errors, I mentioned in my answer. I just understood the question to be, how to catch as broadly as possible, that's why I used Throwable instead.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.