处理资源控制器方法引发的错误

问题描述 投票:0回答:1

我和Laravel 5.6合作,我决定创建一个资源控制器来处理我的一个模型。正确知道我试图从数据库中销毁一条记录,如下所示:

public function destroy(Role $role)
  {
      $role->delete();

      return response([
          'alert' => [
              'type' => 'success',
              'title' => 'Role destroyed!'
          ]
      ], 200);
  }

它就像$role存在一样长。我的问题是,我想在$role不存在这样做的情况下自己处理响应:

return response([
     'alert' => [
         'type' => 'ups!',
         'title' => 'There is no role with the provided id!'
     ]
], 400);

但相反,我得到这样的错误:

"No query results for model [App\\Models\\Role]."

这是我不想要的。

提前致谢!

laravel laravel-5.6
1个回答
2
投票

"No query results for model [App\\Models\\Role]."是Laravel中ModelNotFound例外的标准响应消息。

更改此类异常响应的最佳方法是使用异常处理程序的render函数来响应您想要的任何消息。

例如,你可以做到

if ($e instanceof ModelNotFoundException) {
        $response['type'] = "ups!;
        $response['message'] = "Could not find what you're looking for";
        $response['status'] = Response::HTTP_NOT_FOUND
    }


    return response()->json(['alert' => $response], $response['status']);

另一种方法是确保不会抛出ModelNotFound异常(因此在查询模型时使用->find()而不是->findOrFail())然后如果没有返回结果则使用abort helper:

abort(400, 'Role not found');

要么

return response(['alert' => [
    'type' => 'ups!', 
    'title' => 'There is no role with the provided id!']
],400);
© www.soinside.com 2019 - 2024. All rights reserved.