繁体   English   中英

Laravel 5 API与Dingo

[英]Laravel 5 API with Dingo

我正在使用Laravel 5和Dingo构建API。 如何捕获没有定义路由的任何请求? 我希望我的API始终使用特定格式的JSON响应进行响应。

例如,如果我有一条路线:$ api-> get('somepage','mycontroller @ mymethod');

假如没有定义路由,我该如何处理有人为同一个uri创建帖子的情况?

基本上发生的事情是Laravel抛出一个MethodNotAllowedHttpException。

我试过这个:

    Route::any('/{all}', function ($all) 
    {
        $errorResponse = [
            'Message' => 'Error',
            'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
        ];
        return Response::json($errorResponse, 400);     //400 = Bad Request
    })->where(['all' => '.*']);

但我不断抛出MethodNotAllowedHttpException。

有没有办法可以做到这一点? 使用中间件? 其他形式的捕获所有路线?

编辑:

尝试将此添加到app \\ Exceptions \\ Handler.php

public function render($request, Exception $e)
{
    dd($e);
    if ($e instanceof MethodNotAllowedHttpException) {
        $errorResponse = [
            'Message' => 'Error',
            'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
        ];
        return Response::json($errorResponse, 400);
    }
    return parent::render($request, $e);        
}

它没有效果。 我做了dump-autoload和所有这些。 我甚至添加了dd($ e),它没有效果。 这对我来说似乎很奇怪。

编辑 - 解决方案

弄清楚了。 虽然詹姆斯的回答让我思考正确的方向,但发生的事情是Dingo正在压倒错误处理。 要自定义此错误的响应,您必须修改app \\ Providers \\ AppServiceProvider.php。 像这样启动启动功能(默认为空)

public function boot()
{
    app('Dingo\Api\Exception\Handler')->register(function (MethodNotAllowedHttpException $exception) {
         $errorResponse = [
            'Message' => 'Error',
            'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
        ];
        return Response::make($errorResponse, 400);
    });
}

接受詹姆斯的回答,因为它让我朝着正确的方向前进。

希望这有助于某人:)这占据了我晚上更好的部分......呃

您可以通过捕获异常并检查它是否是MethodNotAllowedHttpException的实例,在app/Exceptions/Handler.php执行此操作。

如果是,则可以执行逻辑以返回自定义错误响应。

在同一位置,如果要捕获NotFoundHttpException实例,还可以自定义检查。

// app/Exceptions/Handler.php

public function render($request, Exception $e)
    {
        if ($e instanceof MethodNotAllowedHttpException) {
            $errorResponse = [
                'Message' => 'Error',
                'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
            ];
            return Response::json($errorResponse, 400);
        }

        if($e instanceof NotFoundHttpException)
        {
            $errorResponse = [
                'Message' => 'Error',
                'Error' => ['data' => 'Sorry, that resource is not found or the method is not allowed.' ]
            ];
            return Response::json($errorResponse, 400);
        }

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

暂无
暂无

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

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