Laravel 5 API 与野狗

Laravel 5 API with Dingo

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

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

假设路由未定义,我如何处理有人创建 post 到同一 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) 但它没有任何效果。这对我来说似乎很奇怪。

编辑 - 解决方案

想通了。虽然 James 的回答让我朝着正确的方向思考,但实际情况是 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);
    });
}

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

希望这对某人有所帮助 :) 这占据了我晚上的大部分时间....呃

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

如果是,那么您可以执行 return 您的自定义错误响应的逻辑。

在同一个地方,如果你想捕获 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);
    }