400和500的JSON错误响应的良好实践

时间:2017-12-08 12:28:59

标签: json rest

我已阅读了许多RESTful API设计模式资源 但我对决定API没有信心。

似乎不存在标准的JSON响应格式。 我需要有关Json错误响应的建议,如下所示。

401
jwt令牌相关失败

{
  code:1,
  message: "no access token"
}

{
  code:2,
  message: "invalid access token"
}

{
  code:3,
  message: "expired access token"
}

400
客户输入参数不足

{
  code:20,
  message: "input paramter 'search' is missing"
}

客户的无效值请求

{
  code:21,
  message: "invalid serial no"
}

客户的无效请求格式

{
  code:22,
  message: "input parameter indate is invalid date format"
}

500 另一个网格化服务器的问题

{
  code:30,
  message: "no reply from external server API"
}

程序逻辑错误(例如异常)

{
  code:31,
  message: "internal server error"
}

对于500个案例,我认为客户还需要更多信息。 另一个问题是“需要错误代码吗?”

1 个答案:

答案 0 :(得分:1)

您可以使用 HTTP API问题详细信息

这是一个很好的格式,可以轻松扩展,为客户提供一个好的方法来适当地对每个错误/问题作出反应。

https://tools.ietf.org/html/rfc7807

以下是RFC的一个例子:

if ($this->input->post('save')) {
    $this->form_validation->set_rules('student_name', 'Student Name', 'required');
    $this->form_validation->set_rules('student_email', 'Student Email', 'required|valid_email|is_unique[std_info.std_email]', ['is_unique' => 'The {field} field is alredy exits']);
    $this->form_validation->set_message('valid_email', 'This {field} field is invalid');
    if (!$this->form_validation->run()) {
        $this->load->view('create', $data);
        return;
    }
    $config['upload_path'] = 'images';
    $config['allowed_types'] = 'jpg|png';
    $config['max_size'] = 1000;
    $config['overwrite'] = false;
    $config['encrypt_name'] = true;
    $this->load->library('upload', $config);
    $this->upload->initialize($config);
    if (!$this->upload->do_upload('user_image')) {
        $this->session->set_flashdata('message', $this->upload->display_errors());
        $this->load->view('create', $data);
        return;
    }
    $image_data = $this->upload->data();
    $config2['image_library'] = 'gd2';
    $config2['source_image'] = $image_data['full_path']; //get original image
    //$config2['new_image'] = 'images'; //save as new image //need to create thumbs first
    $config2['maintain_ratio'] = false;
    $config2['create_thumb'] = false;
    //$config2['overwrite'] = false;
    $config2['width'] = 300;
    $config2['height'] = 300;
    $this->load->library('image_lib', $config2);
    if (!$this->image_lib->resize()) {
        $this->session->set_flashdata('message', $this->image_lib->display_errors());
        $this->load->view('create', $data);
        return;
    }
    $receive = $this->input->post(['student_name', 'student_email', 'student_about'], TRUE);
    $param = [
        'std_name' => (string) $receive['student_name'],
        'std_email' => (string) $receive['student_email'],
        'std_about' => (string) $receive['student_about'],
        'images' => $image_data['file_name']
    ];
    $response = $this->std_model->insert_data('std_info', $param);
    if ($response['status'] === 'success') {
        redirect('welcome');
    }
}