4

我正在使用 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);        
}

它没有效果。我做了转储自动加载和所有这些。我什至添加了 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);
    });
}

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

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

4

1 回答 1

3

您可以app/Exceptions/Handler.php通过捕获异常并检查它是否是MethodNotAllowedHttpException.

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

在同一个地方,如果您想捕获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);
    }
于 2016-04-02T07:00:03.813 回答