Luca D'Alberti
Luca D'Alberti

Reputation: 4849

error 500 setting header to return 400 error PHP

I'm developing a RESTful web service and, honestly, it is my first ws. I decided to use PHP because I think that I know that language.

This is my RestHandler object, but when I debug the request, accessing to a method not implemented, with Charles, it returns the right response, but 500 error instead of 400. Why?

class RestHandler {

    private $method;
    private $actionName;

    /**
     * @param $method
     * @param $action
     */
    public function __construct($method, $action)
    {
        $this->method = $method;
        $this->actionName = $action;

        if (isset($this->method) && isset($this->actionName))
        {
            if (! method_exists($this, $this->actionName))
            {
                // Action is not implemented in the object.
                $this->handleErrorReturning("Not implemented method.", 400);
                return;
            }
            // OK, proceed with actions
            $this->handleProceedRequest();
        }
        else
        {
            // Return error 406 Missing parameter
            $this->handleErrorReturning("Missing parameter", 406);
        }
    }

    private function handleProceedRequest()
    {
        if (strcasecmp($this->method, "get") == 0)
        {
            // No JSON to read
        }
    }

    /**
     * @param $errorDescription
     * @param $errorCode
     */
    private function handleErrorReturning($errorDescription, $errorCode)
    {
        header($_SERVER["SERVER_PROTOCOL"]." ".$errorDescription." ".$errorCode);
        header('Content-Type: application/json; charset=utf-8');
        $errorResponse = new ResponseError($errorCode, $errorDescription);
        echo $errorResponse;
    }
}

This is the Charles snapshot Charles snapshot

SOLVED I inverted errorDescription with errorCode and now it works. It was a stupid error. Thanks

Upvotes: 0

Views: 1266

Answers (1)

RhapX
RhapX

Reputation: 1683

Try setting your header like this:

header($_SERVER['SERVER_PROTOCOL'] . ' Not implemented method', true, 400);

Upvotes: 1

Related Questions