We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

BeforeException multiple HTTP code errors

Hi,

How can I do when my controller returns different response (400, 403, 404, 410...) to show the good view in the dispatcher ? I want to create a view for each errors.

Here is my beforeException function :

    public function beforeException($event, $dispatcher, $exception) {

        if ($exception instanceof DispatcherException) {
            switch ($exception->getCode()) {
                case Dispatcher::EXCEPTION_HANDLER_NOT_FOUND:
                case Dispatcher::EXCEPTION_ACTION_NOT_FOUND:
                    $dispatcher->forward(array(
                        'controller' => 'errors',
                        'action' => 'show404'
                    ));
                    return false;
            }
        }

         $dispatcher->forward(array(
            'controller' => 'errors',
            'action'     => 'show500'
         ));

        return false;
    }

So, could you tell me how grab the 404 errors or the 410 errors here ?

You could extract the status code from the response: $this->response->getStatusCode().

It will return a string for eg: 401 Unauthorized

By default $this->response->getStatusCode() returns false, so I think you manually have to set the code with $this->response->setStatusCode($code)

edited May '16

Ok and how can I do to trigger EXCEPTION_ACTION_NOT_FOUND ? Because In my case I'll never pass into this condition because I return 404 like this :

$response = new Response();
$response->setStatusCode(404, 'Not found');
return $response;

And this code is inside my Action. Then I don't know how to trigger this exception.

Maybe I have to redirect to my ErrorsController manually without pass into the beforeException event ?



77.7k
Accepted
answer
edited May '16

Try throwing an instance of Phalcon\Mvc\Dispatcher\Exception with the appropriate code as second argument

throw new Phalcon\Mvc\Dispatcher\Exception('Not found', Phalcon\Dispatcher::EXCEPTION_ACTION_NOT_FOUND);

But note that this code is NOT the same as http status codes!

Ok thanks I'll try this.