Search code examples
phpamphp

Why am I getting "Error: Call to a member function end() on null" using Aerys?


I'm trying to put aerys on top of my cms but getting error. As I see the backend returns not null value - #1 in stacktrace but it doesn't reach $resp->end(). I'm stucked trying to get that value to the end().

Code example

$router = router()
        ->route("GET", "/exchangews", $websocket)
        ->route('*', '/{resource}/?', function (Aerys\Request $req, Aerys\Response $res, array $route) {

            // copy params and make scalar the single values
            $params = [];
            foreach(($param = yield $req->getAllParams()) as $key => $val){ 
                if(count($val)==1)$params[$key] = array_pop($val);
            }
            $headers = $req->getAllHeaders();

            $bodyProm = Amp\call( function() use($params, $headers, $route){
                try{
                    $lead = new RequestHandler($headers, array_merge($params, $route));
                    $body = $lead->proccess();
                    return $body;
                }catch(\Exception $e){
                    //
                }
            });
            $body = yield $bodyProm;
            // run my application
            $resp->end($body);

            # matched by e.g. /user/rdlowrey/42
            # but not by /user/bwoebi/foo (note the regex requiring digits)
            # $res->end("The user with name {$route['name']} and id {$route['id']} has been requested!");
        });

Stack trace:

    Error: Call to a member function end() on null in /Library/WebServer/Documents/ingine/index_aerys.php:47
    Stack trace:
    #0 [internal function]: {closure}(Object(Aerys\StandardRequest), Object(Aerys\StandardResponse), Array)
    #1 /Library/WebServer/Documents/ingine/vendor/amphp/amp/lib/Coroutine.php(74): Generator->send('<!DOCTYPE html ...')
    #2 /Library/WebServer/Documents/ingine/vendor/amphp/amp/lib/Success.php(33): Amp\Coroutine->Amp\{closure}(NULL, Array)
....

What's wrong?


Solution

  • This seems to be a simple typo. You define Aerys\Response $res as parameter, but then use $resp and try to call a function on it, which is undefined. You should enable error reporting during development. PHP should emit a notice for an undefined variable there.

    Additionally, your Amp\call is unnecessary. You can simply write it as:

    try {
        $lead = new RequestHandler($headers, array_merge($params, $route));
        $body = yield $lead->proccess();
    } catch(\Exception $e){
        // handle error
    }