[eluser]Unknown[/eluser]
Hello.
I have a function in controller which returns information about the company in json format.
Here is the code:
Code:
public function getCompanyInfo() {
if (!$this->input->get('company_id')) {
exit;
}
$company_info = $this->companies_model->getCompanyInfo($this->input->get('company_id'));
if (count($company_info) == 0) {
exit;
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($company_info));
}
I'm really confused with the right way to handle bad input data. There are several situations, for example there is no company_id in get params, or (in other function) the data is not valid at all (for example - not valid email).
In these cases I want to return some http error code (like 400 - bad request), and some json informatio (like {"error":"bad_input"}). Not sure though if returning 400 is a good solution, but another guy who works with javascript/ajax told me that there are some javascript functions which handle http errors like 400 and it's a good thing to return 400 with json explanation.
My first question is: is it ok to return 400 + json info as a solution to handle bad input data? Now I have only exit to prevent errors or hack attempts.
My seconf question is: if I have a function, where there are a lot of places where I should interrupt execution of function, and return some headers with json, how would I do that? set_content_type, set_headers, set_output works if I put them in the end of function, but for example in my case above I want something like:
Code:
if (!$this->input->get('company_id')) {
$this->output
->set_status_header('400');
->set_content_type('application/json')
->set_output(json_encode(array('error' => 'bad_input')));
exit;
}
and the same in
Code:
if (count($company_info) == 0) { ... }
(in case the ID is wrong so the model won't return anything)
Could you explain how to deal with such situations in a good maner, I have a feeling that my code is a mess.
And one more thing: how could I use instead of $this->output->... my own function for all controllers? for example:
Code:
function bad_input() {
$this->output
->set_status_header('400');
->set_content_type('application/json')
->set_output(json_encode(array('error' => 'bad_input')));
exit;
}
If I put it in a helper it won't work because of "$this". But If I decide to rename 'error'=>'bad input data from user' I'll have to do that in several controllers which is not good
I'll appreciate any advices, thanks in advance, and sorry for my poor english