Catching exceptions from dispatch event listeners

Hello,

I want to use exceptions for error handling, however whenever I throw anything inside dispatch event listeners, they are not caught inside the framework, even though I have my beforeException event listener. It only catches exceptions from within controllers action.

What should I do to utilize exceptions inside those event listeners?

Thank you very much

edited Jun '16

Well, wait, wouldn't this mean that you could possibly have recursion ? You mean in beforeException even listener you want to throw exception which should be again catch in beforeException ? I don't think it's possible, also i think you shouldn't do stuff like this.

You can always use set_error_handler from php



381

I don't think so. When you catch an exception, you surrender your control to the catch block, regardless of how many blocks you might be in. Meaning that once you jump out of the dispatch scope, there won't be any listener that could trigger nesting of exceptions. And I want to catch exceptions from "beforeExecute" or "beforeDispatchLoop". And handle them in "beforeException".



381

Also, I want to handle the error inside ErrorController, which I can not do when I get thrown outside the application.

Try - catch block is done only on executing your action - https://github.com/phalcon/cphalcon/blob/master/phalcon/dispatcher.zep#L508(which checks for beforeException listener). This is why throwing exception in beforeExecute is not catch be beforeException. You need to currently use seterrorhandler or do PR for fixing current behaviour if you thinks it's necessary.



381

So my only option to do what I actually want without having to put try/catch in every listener is to implement my own dispatcher and put explicit catch around the dispatch method? :)

No, you can use set_error_handler.



381

I assume you mean set_exception_handler. Which, again, is completely outside the application scope, meaning I can simply put $app->handle(); in try/catch block and the result would be the same. However, as I mentioned, I would like to catch the exceptions coming from dispatcher (both direct and indirect) inside the application, forward them to ErrorController and process them there.

Well yea, then you right, you need extend dispatcher. Or as i already wrote - you can do PR with this "fix".