Home > Backend Development > PHP Tutorial > yii2 关于自定义errorHandler的疑问

yii2 关于自定义errorHandler的疑问

WBOY
Release: 2016-06-06 20:12:11
Original
1768 people have browsed it

<code>//配置文件web.php加了下面一个配置
'errorHandler' => [
    'errorAction' => 'test/error',
],

//TestController.php文件的内容

namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\HttpException;

class TestController extends Controller
{
    public function actionIndex()
    {
        throw new HttpException(409, 'adf');
    }
    public function actionError()
    {
        echo 'a';die;
    }
}
</code>
Copy after login
Copy after login

这样请求index会输出a,但是如果我在配置文件web.php中加上下面的配置项,将响应格式改成json

<code>'response' => [
    'format' => yii\web\Response::FORMAT_JSON,
    'charset' => 'UTF-8',
],</code>
Copy after login
Copy after login

现在请求index,就不输出a了,这是为什么?

这个问题我追了一下源代码,自己已经有答案了。是在yii\web\ErrorHandler的renderException方法中,如果响应格式是json就会走分支的最后一段,调用的是convertExceptionToArray方法,而没走定义的errorAction方法中

回复内容:

<code>//配置文件web.php加了下面一个配置
'errorHandler' => [
    'errorAction' => 'test/error',
],

//TestController.php文件的内容

namespace app\controllers;
use Yii;
use yii\web\Controller;
use yii\web\HttpException;

class TestController extends Controller
{
    public function actionIndex()
    {
        throw new HttpException(409, 'adf');
    }
    public function actionError()
    {
        echo 'a';die;
    }
}
</code>
Copy after login
Copy after login

这样请求index会输出a,但是如果我在配置文件web.php中加上下面的配置项,将响应格式改成json

<code>'response' => [
    'format' => yii\web\Response::FORMAT_JSON,
    'charset' => 'UTF-8',
],</code>
Copy after login
Copy after login

现在请求index,就不输出a了,这是为什么?

这个问题我追了一下源代码,自己已经有答案了。是在yii\web\ErrorHandler的renderException方法中,如果响应格式是json就会走分支的最后一段,调用的是convertExceptionToArray方法,而没走定义的errorAction方法中

如果要响应JSON,你要返回一个数组

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template