2019-05-15 11:03:17 4461瀏覽
有沒有小伙伴開發(fā)某種RESTful API.發(fā)生一些錯(cuò)誤呢?本篇文章扣丁學(xué)堂PHP培訓(xùn)小編給讀者們分享一下PHP使Laravel為JSON REST API返回自定義錯(cuò)誤的問題,對此感興趣的小伙伴就隨小編來了解一下吧,希望對小伙伴們有所幫助。
問題是:我希望他用鍵“代碼”和“消息”拋出一個(gè)json形成的數(shù)組,每個(gè)數(shù)組都包含上述數(shù)據(jù)。
有沒有人知道是否可能,如果是,我該怎么做?
去你的app / start / global.php.
這將將401和404的所有錯(cuò)誤轉(zhuǎn)換為自定義json錯(cuò)誤,而不是Whoops stacktrace.加這個(gè):
這是處理此錯(cuò)誤的眾多選項(xiàng)之一。
制作API最好創(chuàng)建自己的幫助器,如Responser :: error(400,'damn'),擴(kuò)展了Response類。
有點(diǎn)像:
Array
(
[code] => 401
[message] => "Invalid User"
)
App::error(function(Exception $exception, $code)
{
Log::error($exception);
$message = $exception->getMessage();
// switch statements provided in case you need to add
// additional logic for specific error code.
switch ($code) {
case 401:
return Response::json(array(
'code' => 401,
'message' => $message
), 401);
case 404:
$message = (!$message ? $message = 'the requested resource was not found' : $message);
return Response::json(array(
'code' => 404,
'message' => $message
), 404);
}
});
public static function error($code = 400, $message = null)
{
// check if $message is object and transforms it into an array
if (is_object($message)) { $message = $message->toArray(); }
switch ($code) {
default:
$code_message = 'error_occured';
break;
}
$data = array(
'code' => $code,
'message' => $code_message,
'data' => $message
);
// return an error
return Response::json($data, $code);
}
想要了解更多關(guān)于PHP開發(fā)方面內(nèi)容的小伙伴,請關(guān)注扣丁學(xué)堂PHP培訓(xùn)官網(wǎng)、微信等平臺(tái),扣丁學(xué)堂IT職業(yè)在線學(xué)習(xí)教育有專業(yè)的PHP講師為您指導(dǎo),此外扣丁學(xué)堂老師精心推出的PHP視頻教程定能讓你快速掌握PHP從入門到精通開發(fā)實(shí)戰(zhàn)技能??鄱W(xué)堂PHP技術(shù)交流群:374332265。
【關(guān)注微信公眾號獲取更多學(xué)習(xí)資料】 【掃碼進(jìn)入Python全棧開發(fā)免費(fèi)公開課】
查看更多關(guān)于“php培訓(xùn)資訊”的相關(guān)文章>>