0

I have a question. I have the folowing condition :

You should return an HTTP 500 status code and more details about the error in the message body. Set the HTTP content type response to “application/json”.The error detail must be in JSON format as described below:

 {
    "ErrorCode" : 402,
    "ErrorMessage" : "Item"
  }

I tried like this :

if(!Gain::verifyIfUserExistByIdm($aOutput['UserId'])){
    header("HTTP/1.0 500 Internal Server Error");
    return json_encode(array('ErrorCode'=>407,'ErrorMessage'=>'Error'));
    die();
}

But not work, can you help me please? Thx in advance

TanGio
  • 766
  • 2
  • 12
  • 34
  • `header('Content-Type: application/json');` – Hanky Panky Jul 20 '15 at 17:26
  • Where I need to add this `header` – TanGio Jul 20 '15 at 17:27
  • I think you want this - http://stackoverflow.com/questions/4162223/how-to-send-500-internal-server-error-error-from-a-php-script, and return is not needed. simply exit; after the header is enough. – ArtisticPhoenix Jul 20 '15 at 17:29
  • 1
    `500` is only for internal servers errors where no other information about the error is available. You should consider using either a more specific `5xx` error code, or use a `4xx` error, if it is a client problem. – Sverri M. Olsen Jul 20 '15 at 17:29
  • Ok, I understand so for example if I want to send the error 402 – TanGio Jul 20 '15 at 17:30
  • @Gigel - please note you should call header in this way only once and only before any other output – ArtisticPhoenix Jul 20 '15 at 17:31
  • ah, ok just use the header header('Content-Type: application/json'); just prior to outputting the data then, – ArtisticPhoenix Jul 20 '15 at 17:32
  • Not work like this : `header("HTTP/1.0 500 Internal Server Error"); header('Content-Type: application/json'); return json_encode(array('ErrorCode'=>407,'ErrorMessage'=>'Payload decode failed'));` – TanGio Jul 20 '15 at 17:34

1 Answers1

2

You need to output the JSON (not just return it), and let the client know that the content is JSON by setting the Content-Type:

// The user does not exist
if ( ! Gain::verifyIfUserExistByIdm($aOutput['UserId'])) {

    // If the user does not exist then "Forbidden" would make sense
    header("HTTP/1.0 403 Forbidden");

    // Let the client know that the output is JSON
    header('Content-Type: application/json');

    // Output the JSON
    echo json_encode(array(
        'ErrorCode'    => 407,
        'ErrorMessage' => 'Error',
    ));
    // Always terminate the script as soon as possible
    // when setting error headers
    die;
}
Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52