Custom Error Page ( 404 )

May '15

Jul '15




So when i started working with Phalcon , i couldn't make a custom error page work , so i took the time of learning the basics and showing you guys how to inplement to your application .

Obs: i am using Phalcon´s multi module ( Frontend & Backend ) MVC , so feel free to adapt to your application.

Step 1 : Setting up Dispatcher Service

So you will need to create a dispatcher service in your project , since i'm working with a multi module application , i have under my config directory a file named services.php , which contains all my services for both modules , such as routing and the database connection.


You will need to add these namespaces :

    use Phalcon\Mvc\Dispatcher\Exception as DispatchException,
    Phalcon\Mvc\Dispatcher as PhDispatcher,
    Phalcon\Events\Manager as EventsManager,

Then create the service ( in my application i don't use Phalcon's OOP $di->set , i set it directly ).

Just copy and paste , you could change the action and the controller if needed.

$di['dispatcher'] = function () {
    $eventsManager = new EventsManager();
    $eventsManager->attach("dispatch:beforeException", function($event, $dispatcher, $exception) {

        if ($exception instanceof DispatchException) {
                'controller' => 'index',
                'action'     => 'error'
            return false;


    $dispatcher = new PhDispatcher();

    return $dispatcher;

Step 2 : The Controller

Since i have forward to the index controller , i just have to create the action and point to a view :

public function errorAction(){


Yep. I have use code like example the above that is very easy, thanks you to share :)

You need implement this only if you have multi-module app (different 404 for each module - 1 dispatcher for 1 module) or if you want more flexible error handling. But more simple solution is just add special route

$router->notFound(array( "controller" => "index", "action" => "route404" ));