Laravel 5 API与Dingo

乔尔·莱格(Joel Leger)

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

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

希望这对某人有帮助:)这占了我大部分时间。

詹姆士

您可以在内部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);
    }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章