简体   繁体   English

通过某些路由前缀捕获未找到错误 [Laravel]

[英]Catch not found error by certain route prefix [Laravel]

I'm building web api along side with website in laravel 5.2, when user visit unavailable url on my web like http://stage.dev/unavailable/link then it will throw on 404 page on errors view resource, then i want to catch with different way if user try to access my API with unavailable url like http//stage.dev/api/v1/unavailable/link , then i want to return json/xml response我正在与 laravel 5.2 中的网站一起构建 web api,当用户访问我的 web 上不可用的 url 时,如http://stage.dev/unavailable/link然后它会在错误视图资源的 404 页面上抛出,然后我想如果用户尝试使用诸如http//stage.dev/api/v1/unavailable/link类的不可用 url 访问我的 API,则以不同的方式捕获,然后我想返回json/xml响应

{
  'status' : 'not found',
  'code' : 404,
  'data' : []
}

not the view, is there a way to detect it by url prefix 'api/*' or how.., maybe another approach with similar result, so the device/client which access it could proceed by standard format (i have simple format in all json response)不是视图,有没有办法通过 url 前缀“api/*”或如何检测它,也许是另一种具有类似结果的方法,因此访问它的设备/客户端可以通过标准格式进行(我在所有 json 响应)

{
  'status' : 'success|failed|restrict|...',
  'api_id' : '...',
  'token' : '...',
  'data' : [
    {'...' : '...'},
    {'...' : '...'},
    ...
  ]
}

SOLVED解决了

I figure out something after read answer from Chris and Alexey this approach works for me i add couples of lines in handler.php at render() method,在阅读ChrisAlexey 的回答后,我想出了一些办法,这种方法对我handler.php ,我在handler.php中的render()方法中添加了handler.php行,

    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());
        }
    }

my header request respond 404 error code and return json data like i want..我的标头请求响应 404 错误代码并返回我想要的 json 数据..

Maybe there's a better way to do that, but you could create custom error 404 handler.也许有更好的方法来做到这一点,但您可以创建自定义错误 404 处理程序。 Follow this tutorial , but change case 404 part to something like this:按照本教程,但将case 404部分更改为如下所示:

if(str_contains(Request::url(), 'api/v1/')){
    return response()->json(your_json_data_here);
}else{
    return \Response::view('custom.404',array(),404);
}

Inside App\\Exception\\Handler.php you have a render method which can be handy for general purpose error catching and handling.App\\Exception\\Handler.php您有一个render方法,它可以方便地用于通用错误捕获和处理。

In this case you can also use the request()->ajax() method to determine if it's ajax.在这种情况下,您还可以使用request()->ajax()方法来确定它是否是 ajax。 It does this by checking that certain headers are present, in particular:它通过检查某些标头是否存在来做到这一点,特别是:

'XMLHttpRequest' == $this->headers->get('X-Requested-With')

Anyway, back to the render method in Handler.php .无论如何,回到Handler.php的 render 方法。

You can do something like:您可以执行以下操作:

public function render($request, Exception $e)
{        

    if($e instanceof HttpException && $e->getStatusCode() == 404) {
        if (request()->ajax()) {
            return response()->json(['bla' => 'foo']);
        } else {
            return response()->view('le-404');
        }
    }

    return parent::render($request, $e);
}

I figure out something after read answer from Chris and Alexey this approach works for me i add couples of lines in handler.php at render() method,,在阅读ChrisAlexey 的回答后,我想出了一些办法,这种方法对我有用,我在 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());
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM