代码之家  ›  专栏  ›  技术社区  ›  enbermudas

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

  •  0
  • enbermudas  · 技术社区  · 8 年前

    我和你一起工作 Laravel 5.6

    public function destroy(Role $role)
      {
          $role->delete();
    
          return response([
              'alert' => [
                  'type' => 'success',
                  'title' => 'Role destroyed!'
              ]
          ], 200);
      }
    

    它工作得很好,就像 $role 存在。我的问题是,我想处理的情况下,我自己的反应 不存在这样的操作:

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

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

    这是我不想要的。

    提前谢谢!

    1 回复  |  直到 8 年前
        1
  •  2
  •   Joe    8 年前

    这个 "No query results for model [App\\Models\\Role]." 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']);
    

    另一种方法是确保 找不到模型 ->find() 而不是 ->findOrFail() 如果没有返回结果,则使用类似的abort helper:

    abort(400, 'Role not found');
    

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