17

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!

1

1 Answer 1

33

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

    if (!$this->isApiKeyValid()) {
        $this->getResponse()->setStatusCode(401);
        return;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Zend framework 1 : $this->getResponse()->setHttpResponseCode(401);
How do you render a custom 404 page then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.