Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Return custom HTTP status code in Zend Framework 2

I am trying to return a 401 http status-code if a given apikey is not correct:

class MessageRestfulController extends AbstractRestfulController {
    # ...
    public function get($id) {
        if (!$this->isApiKeyValid()) {
            $response = new Response();
            $response->setStatusCode(Response::STATUS_CODE_401);
            return $response;
        }
        # ...
        return new JsonModel(array(
            'data' => array(...)
        ));
    }
} 

For my controller i have added 'strategies' => array('ViewJsonStrategy)' because it is a AbstractRestfulController and should return json if operation was successful.

I am really new to ZF2 and dont know what the correct way is to implement such an exception.

The way i am currently doing it, does not work.

Thanks for your hints!

like image 220
Roman Avatar asked Mar 06 '13 11:03

Roman


1 Answers

Your controller already has a Response object, set the status code on that and just return

    if (!$this->isApiKeyValid()) {
        $this->getResponse()->setStatusCode(401);
        return;
    }
like image 58
Crisp Avatar answered Jan 04 '23 01:01

Crisp