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

Error handler in Micro not working properly

I'm trying to follow this example:

https://docs.phalcon.io/bg/3.2/application-micro#error-handling

But whenever I throw this on a middleware or a controller:

throw new \Exception('abc', 200);

I get this:

{"code":200,"status":"error","message":"abc"}
( ! ) Fatal error: Uncaught Exception: abc in /Users/mike/Sites/notes/server/app/controllers/UserController.php on line 12
( ! ) Exception: abc in /Users/mike/Sites/notes/server/app/controllers/UserController.php on line 12
Call Stack
#   Time    Memory  Function    Location
1   0.0007  408416  {main}( )   .../index.php:0
2   0.0022  435848  handle ( )  .../index.php:80

I thought it would catch that exception. Am I wrong?

edited Jan '18

You throw an exception but to catch it you need to put your executed code inside a try/catch block

try{
 //...
}catch(Exception $e){
    echo $e->getMessage();
}

https://php.net/manual/en/language.exceptions.php

So what does this do then?

$app->error(
    function ($exception) {
        echo json_encode(
            [
                'code'    => $exception->getCode(),
                'status'  => 'error',
                'message' => $exception->getMessage(),
            ]
        );
    }
);

As you can see this code is executed :

{"code":200,"status":"error","message":"abc"}

It seems that you need to catch the Exception to not have the fatal error, or maybe add a die just after the json_encode (sry never used it)

That doesn't seem right. It is an error handler so it's supposed to handle the exception, right?

I'd like to hear some more opinions. Anyone?

As you can see this code is executed :

{"code":200,"status":"error","message":"abc"}

It seems that you need to catch the Exception to not have the fatal error, or maybe add a die just after the json_encode (sry never used it)

I've just test it and that work fine without adding anything to catch ... What version of php / phalcon do you use ? Can you provide more code to check.

edited Jan '18

Wow, really? PHP 7.2.1, Phalcon 3.3.0. Can I know yours?

index.php

namespace Notes;

use Phalcon\Config;
use Phalcon\Db\Adapter\Pdo\Sqlite;
use Phalcon\Mvc\Micro;
use Notes\Middleware\CorsMiddleware;
use Notes\Middleware\PostMiddleware;
use Notes\Middleware\AuthenticationMiddleware;

$app = new Micro();
require __DIR__ . '/../app/config/collections.php';

// ... Middleware, autoloader, config, etc...

$app->notFound(
    function () use ($app) {
        $app->response->setStatusCode(404, 'Not Found');
        $app->response->sendHeaders();
        $app->response->setContent('Not Found');
        $app->response->send();
    }
);
$app->error(
    function ($exception) {
        echo json_encode(
            [
                'code'    => $exception->getCode(),
                'status'  => 'error',
                'message' => $exception->getMessage(),
            ]
        );
    }
);
$app->handle();

collections.php

use Phalcon\Mvc\Micro\Collection;

$indexCollection = new Collection();
$indexCollection->setHandler('Notes\Controllers\IndexController', true);
$indexCollection->get('/', 'index');
$app->mount($indexCollection);

$userCollection = new Collection();
$userCollection->setHandler('Notes\Controllers\UserController', true);
$userCollection->post('/login', 'login');
$app->mount($userCollection);

UserController.php

namespace Notes\Controllers;

use Notes\Controllers\ControllerBase;
use Notes\Models\Users;

class UserController extends ControllerBase
{
    public function login()
    {
        if (!isset($this->request->body->email) or !isset($this->request->body->password)) {
            throw new \Exception('Unspecified email or password.', 400);
        }

        $user = Users::findFirstByEmail($this->request->body->email);

        if (!$user) {
            throw new \Exception('Invalid email or password.', 401);
        }

        throw new \Exception('abc', 200);

        // ...
    }
}
edited Jan '18

Your code seems to be good.
PHP 7.0.22 ; Phalcon 3.2.2
Maybe try only this part of code to see if the pb come from your code or a version bug :

<?php

$app = new Phalcon\Mvc\Micro();

$app->get(
    '/',
    function () {
        throw new \Exception('Some error happened', 401);
    }
);

$app->error(
    function ($exception) {
        echo json_encode(
            [
                'code'    => $exception->getCode(),
                'status'  => 'error',
                'message' => $exception->getMessage(),
            ]
        );
    }
);

$app->handle();
edited Jan '18

Same thing. I've tried it with Phalcon 3.3 on both PHP 7.1 and 7.2. So it's a version bug. I'll post it on GitHub later. Thanks for the help.

Here: https://github.com/phalcon/cphalcon/issues/13262

edited Jul '20

Hi, Miguel Nunes. Thank you to. I predicted that it will be a version bug, but can not be sure. I started my new project site on PHP 7.2 and had the same problem.