(显式绑定)自定义分辨率逻辑和自定义"未找到"行为

时间:2016-07-27 14:40:38

标签: php laravel data-binding exception-handling routes

要将参数显式绑定到模型并抛出自定义异常,我必须(除其他外)将以下内容添加到RouteServiceProvider

$router->model('parameter', 'App\Model', function () {
    throw new CustomNotFoundException;
});

要自定义显式绑定的解析逻辑,我必须将以下内容添加到RouteServiceProvider

$router->bind('parameter', function ($parameter) {
    return App\Model::where('field', $parameter)->first();
});

我的问题是我需要两个但显然不能。如果我将参数绑定到模型并自定义分辨率逻辑,它将不会抛出我的CustomNotFoundException,而是抛出默认的ModelNotFoundException

清楚地总结我的目标:我想自定义分辨率逻辑,如果找不到记录则抛出自定义异常。

编辑我根据@Maraboc的建议试过这个:

$router->bind('parameter', function ($parameter) {
    try {
        return App\Model::where('field' => $parameter)->first();
    } catch (Exception $e) {
        throw new CustomNotFoundException;
    }
});

由于我不知道的原因,这仍然会引发ModelNotFoundException

1 个答案:

答案 0 :(得分:1)

试试这样:

$router->bind('parameter', function ($parameter) {
    try {
         return App\Model::where('field' => $parameter)->firstOrFail();
    } catch (ModelNotFoundException $e) {
        throw new CustomNotFoundException;
    }
});

App\Exceptions\Handler中将其添加到render方法:

if ($e instanceof ModelNotFoundException) {
    throw new CustomNotFoundException;
} 

use Illuminate\Database\Eloquent\ModelNotFoundException as ModelNotFoundException;

或其他解决方法是这样做的:

$router->bind('parameter', function ($parameter) {

    $model = App\Model::where('field' => $parameter)->first();

    if ( ! $model) {
        throw new CustomNotFoundException;
    }

    return $model;
});