0

I want to return data with the HTTP error code in Yii 1. So I used the following way to get the data:

  $code = (0 == $ex->getCode()) ? (isset($ex->statusCode) ? $ex->statusCode : 500) : $ex->getCode();
            $this->setOutputError($ex->getMessage());
            $this->setOutputCode($code);

When I use it this way API returns data with 200 error code as below:

enter image description here

But I want to change header status 200, so I threw exception for this, then output data also changed. I want to change only the header status.

$code = (0 == $ex->getCode()) ? (isset($ex->statusCode) ? $ex->statusCode : 500) : $ex->getCode();
            $this->setOutputError($ex->getMessage());
            $this->setOutputCode($code);

            throw new CHttpException(400, 'Bad Request');

enter image description here

2
  • You can set in your code before return statement \Yii::$app->response->statusCode = XXX where XXX is a new status code. You have put CHttpException in your code - are you sure you are using Yii 2 and not Yii 1? Commented Aug 11, 2020 at 13:10
  • @Bizley sorry Yii 1 Commented Aug 12, 2020 at 4:18

1 Answer 1

1

Yii 1.1 does not have response abstraction, you need to use http_response_code() to change response status code:

$code = (0 == $ex->getCode()) ? (isset($ex->statusCode) ? $ex->statusCode : 500) : $ex->getCode();
$this->setOutputError($ex->getMessage());
$this->setOutputCode($code);

http_response_code(400);

Alternatively you may also use header(), but this is more tricky.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.