Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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)



12.6k
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 ?



35.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!



12.6k

Ok thanks I'll try this.