Search code examples
phpkohanakohana-3

Kohana 3.x - Return from action ASAP if error encountered


Is there a kohana equivalent to the following (derived from Symfony 1.4):

public function ajax_win() {

    try {
        ...
    } catch Exception($e) {

        $response['errors'] = array($e->getMessage());

        $this->template->content = json_encode($response);

        // Id like to return here, early return if error encountered
        // Symfony example
        // Is there a Kohana counterpart, or just do empty return?
        return sfView::NONE;
    }

    // More code here, which is why I want early return, so I don't have to nest conditionals
    ....
}

Solution

  • So you are in a situation inside a Controller's action and don't want any of the other content to be shown but your JSON encoded variable.

    You don't need to return anything, as this is not how Controllers work. However, you need to modify $this->response.

    If you are in the environment of Controller_Template, it is also important to set $this->auto_render to FALSE (or something that is not TRUE), so the after() method does not override everything you tried.

    This code is untested but should do the trick.

    public function ajax_win() {
    
        try {
            ...
        } catch Exception($e) {
            $data['errors'] = array($e->getMessage());
            $response = new Response();
            $response->body(json_encode($data));
            $this->response = $response;
            return;
        }
    
        // More code here, which is why I want early return, so I don't have to nest conditionals
        ....
    }
    

    For more information, you can check the guide, where the Request Flow of an application is described in detail.