处理资源控制器方法抛出的错误

Handling error thrown by resource controller's method

我正在与 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]."

这是我不想要的。

提前致谢!

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

像这样更改异常响应的最佳方法是使用异常处理程序的呈现函数来响应您想要的任何消息。

例如你可以做

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(400, 'Role not found');

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