John P
John P

Reputation: 1221

Yii2 beginner. Display REST exception handling

In my controller, I extend the Controller class instead of ActiveController

I have a simple actionIndex() method:

public function actionIndex(){

    return json_encode(["text" => "some text"]);
}

When I access the certain route in browser, in the debugger, I see that this function is executing (the breakpoint stops inside the function), but I get 500 status code (Internal server error). How can I find the cause of the error? I have implemented the actionError() method, but it is not executing.

    public function actionError() {
    $exception = Yii::$app->errorHandler->exception;
    if ($exception !== null) {
        return $this->render('error', ['exception' => $exception]);
    }
}

If I put the logic of the actionError() method in the actionIndex(), the $exception variable is null

The only output I get is:

{
name: "PHP Warning",
message: "Expected array for frame 0",
code: 2,
type: "yii\base\ErrorException",
file: "Unknown",
line: 0,
stack-trace: []
}

but it's warning, not error. May this cause the status code 500?

How can I get the error? Thanks!

Upvotes: 1

Views: 406

Answers (2)

Mat
Mat

Reputation: 2154

According to this thread https://github.com/yiisoft/yii2/issues/11120 this is related to Xdebug for Yii 2 < 2.0.9. When handling an exception, XDebug modifies the exception and Yii2 was not able to handle it correctly.

So several possible solutions here

  • The best idea is to update Yii2 to a version >= 2.0.9
  • Also you sould correct the source of the exception (the warning). It is never a good idea to have warnings. It can hide some more issues.
  • And as a workaround, you can disable XDebug. It is very useful during development but must be disabled in production in all cases.

Upvotes: 1

karpy47
karpy47

Reputation: 900

Don't know about your error, but there is generally no need to return a response as json encoded. Yii checks the Accept-header of the request and adjust output accordingly. In your case I would just use:

public function actionIndex()
{
    return ["text" => "some text"];
}

Possibly it might also solve your error...

Upvotes: 0

Related Questions