在yii2 REST API中自定义错误消息

时间:2016-06-13 07:22:07

标签: api rest error-handling yii2 yii2-basic-app

我想自定义以下错误消息

Error 404: Not Found
{
    "name": "Not Found",
    "message": "Object not found: 6",
    "code": 0,
    "status": 404,
    "type": "yii\\web\\NotFoundHttpException"
}

为:

Error 404: Not Found
{
    "name": "Not Found",
    "message": "Country not found for: 6",
    "code": 404,
    "status": Error
}

哪里需要编写此自定义代码?

3 个答案:

答案 0 :(得分:1)

您需要覆写扩展yii \ web \ ErrorHandler的errorHandler,只是convertExceptionToArray方法

$ host cheetahtemplate.org
cheetahtemplate.org has address 185.199.111.153
cheetahtemplate.org has address 185.199.108.153
cheetahtemplate.org has address 185.199.109.153
cheetahtemplate.org has address 185.199.110.153

$ host www.cheetahtemplate.org
www.cheetahtemplate.org is an alias for cheetahtemplate3.github.io.

上面的代码来自Yii,您只需要对其稍作调整。 然后将其添加到配置中:(通常是web.php)

/**
 * Converts an exception into an array.
 * @param \Exception|\Error $exception the exception being converted
 * @return array the array representation of the exception.
 */
protected function convertExceptionToArray($exception)
{
    if (!YII_DEBUG && !$exception instanceof UserException && !$exception instanceof HttpException) {
        $exception = new HttpException(500, Yii::t('yii', 'An internal server error occurred.'));
    }

    $array = [
        'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception',
        'message' => $exception->getMessage(),
        'code' => $exception->getCode(),
    ];
    if ($exception instanceof HttpException) {
        $array['status'] = $exception->statusCode;
    }
    if (YII_DEBUG) {
        $array['type'] = get_class($exception);
        if (!$exception instanceof UserException) {
            $array['file'] = $exception->getFile();
            $array['line'] = $exception->getLine();
            $array['stack-trace'] = explode("\n", $exception->getTraceAsString());
            if ($exception instanceof \yii\db\Exception) {
                $array['error-info'] = $exception->errorInfo;
            }
        }
    }
    if (($prev = $exception->getPrevious()) !== null) {
        $array['previous'] = $this->convertExceptionToArray($prev);
    }

    return $array;
}

答案 1 :(得分:0)

尝试一下(例如config / web.php):

return [
    // ...
    'components' => [
        // ...
        'response' => [
            // ...
            'on beforeSend' => function (yii\base\Event $event) {
                $response = $event->sender;
                if (404 === $response->statusCode && is_array($response->data)) {
                    $response->data['code'] = $response->data['status'];
                    $response->data['status'] = 'Error';
                    unset($response->data['type']);
                }
            },
        ],

答案 2 :(得分:0)

我不确定我所做的是对还是错,但是它能奏效。 只需创建一个名为ErrorMsg.php的新自定义php文件

<?php
use Yii;
use yii\web\HttpException;
class ErrorMsg extends \Exception
{
    
    public static function customErrorMsg($error_code,$message = null, $code = 0, \Exception $previous = null,$extra_content=NULL)
    {
        $httpException = new HttpException($error_code,$message,$code,$previous);
        Yii::$app->response->statusCode = $error_code;
        $custom_err = array(
                            'name'=> $httpException->getName(),
                            'message' => $message,
                            'code' => $code,
                            'extraContent' => $content,
                            'status' => $error_code
        );
        return $custom_err;
    }

,然后在所需位置调用函数。例子

return ErrorMsg::customErrorMsg(400,"Message Here",11,NULL,"Extra Content Here");