我正在 Laravel 5.2 中与网站一起构建 Web api,当用户访问我的网站上不可用的 url(例如 http://stage.dev/unavailable/link
)时,它将抛出 404页面上的错误查看资源,那么如果用户尝试使用不可用的 url(例如 http//stage.dev/api/v1/unavailable/link
)访问我的 API,那么我想以不同的方式捕获,然后我想要返回 json/xml
响应
{
'status' : 'not found',
'code' : 404,
'data' : []
}
不是 View ,有没有办法通过 url 前缀“api/*”来检测它或者如何..,也许是另一种具有类似结果的方法,因此访问它的设备/客户端可以按标准格式进行(我有所有 json 响应中的简单格式)
{
'status' : 'success|failed|restrict|...',
'api_id' : '...',
'token' : '...',
'data' : [
{'...' : '...'},
{'...' : '...'},
...
]
}
已解决
阅读 Chris 的答案后我发现了一些东西和 Alexey这种方法对我有用,我在 handler.php
的 render()
方法中添加了几行,
if($e instanceof ModelNotFoundException || $this->isHttpException($e)) {
if($request->segment(1) == 'api' || $request->ajax()){
$e = new NotFoundHttpException($e->getMessage(), $e);
$result = collect([
'request_id' => uniqid(),
'status' => $e->getStatusCode(),
'timestamp' => Carbon::now(),
]);
return response($result, $e->getStatusCode());
}
}
我的 header 请求响应 404 错误代码并返回我想要的 json 数据..
最佳答案
也许有更好的方法来做到这一点,但您可以创建自定义错误 404 处理程序。关注 this tutorial ,但将 case 404
部分更改为如下所示:
if(str_contains(Request::url(), 'api/v1/')){
return response()->json(your_json_data_here);
}else{
return \Response::view('custom.404',array(),404);
}
关于php - 通过某些路由前缀捕获未找到错误 [Laravel],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36247119/