Search code examples
phpexceptiontypo3typo3-7.6.x

How to throw an exception in your Extension?


In an Extbase extension, the need may arise to inform the user about an error or exception.

In my case, I have to parse some data from a potentially bad source. So the extension has to validate this data. And if the data is invalid, it needs to throw an exception that then can be handled by TYPO3.

However, I can only find information about how the exception and error handlers works, but no information on how to correctly throw an exception from inside an extension.

So what is the intended way to throw an exception from inside an Extbase extension?

Expected result

If I produce a syntax error, TYPO3 displays a message similar to this: enter image description here (Taken from the core API reference.)

That is what I would expect a correctly thrown error or exception to look like.

What I tried

Edit: I tried throwing an error like this:

throw new \Exception('Invalid data');

However, all the frontend displays is

Oops, an error occurred! Code: 20160721101726b5339896

Another possible way to produce an error:

$GLOBALS['TSFE']->pageNotFoundAndExit('Invalid data');

However, this shows a Page Not Found error instead of the expected exception.


Solution

  • You implicitly asked 2 questions:

    1. How do I correctly throw an exception in my code?

    I think, that was correct, what you did: Just use PHP \Exception or a suitable exception inherited from \Exception:

    throw new \UnexpectedValueException('Invalid data');
    
    1. Once an exception has been thrown, how do I see more information?

    This has already been answered quite well: https://stackoverflow.com/a/34067853/2444812

    On a development system:

    • set configuration preset "debug"
    • Add TypoScript on start page: config.contentObjectExceptionHandler = 0

    see Error and ExceptionHandling Example

    On a production system:

    You usually do not want to see full stack traces in the frontend. That is why config.contentObjectExceptionHandler is usually set to default, which only shows Oops, an error occurred! Code: 20160721101726b5339896 on the rendered page. Using this code, you can look in the logs (if things are logged and what is logged where always depends on the configuration of the logging system):

    • sys_log : see "Log" in the backend
    • logfile: var/logs/*.log (see Logging with TYPO3). May be typo3temp/logs on older versions and typo3temp/var/logs/ on non-Composer systems.