gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:49:47 27 4
gpt4 key购买 nike

我想自定义以下错误消息

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
}

需要在哪里编写此定制代码?

最佳答案

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

/**
* 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;
}

上面的代码来自Yii,您只需要对其稍作调整。
然后将其添加到配置中:(通常是web.php)
    'errorHandler' => [
'class' => 'your\namespace\YourErrHandler',
],

关于api - 在yii2 REST API中自定义错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37783855/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com