【问题标题】:Laravel send json response from inner functionLaravel 从内部函数发送 json 响应
【发布时间】:2020-03-25 10:34:56
【问题描述】:

所以我正在构建一个 API。 但是我不断地从内部函数返回一个 json 响应。

如果我执行以下操作,则 laravel 会向客户端发送积压或错误日志。这不应该在 api 中发生。那么你如何在 Laravel 中做到这一点呢?

我想立即返回 json 并停止执行而不向客户端显示任何其他信息

public function functionThatIsCalledByClient($data)
{
     $this->validateSomething($data);
}

private function validateSomething($data)
{
    if(! $data ) ) return response()->json(['error' => 'some message'], 400)->send();

    return true;
}

【问题讨论】:

  • 所以... 将validateSomething 的结果存储到变量中,检查其内容,如果不是布尔值,则返回?
  • 如果你这样做 10 次,最终会得到重复的代码,因为 send() 添加了各种我不想要的东西。

标签: php laravel


【解决方案1】:

您可以为此使用 abort 助手,对于复杂的情况,您可以使用 error handling

如果中止:

private function validateSomething($data)
{
    if(! $data )  // you can create a custom helper function to wrap this code.
       abort(400, json_encode(['error'=>'some error']), ['Content-Type: application/json']);

    return true;
}

如果是通用处理程序:

private function validateSomething($data)
{
    if(! $data ) 
       throw new \Exception('some message');

    return true;
}

内部app/Exceptions/Handler.php@render

public function render($request, Exception $e)
{
    if($e instanceof Exception)
        return response()
                ->json(['error' => $e->getMessage()], 400);
                //->send(); should not be necessary
}

【讨论】:

  • 谢谢,你让我找到了答案!在我的情况下 abort 不起作用,之前使用过,因为错误处理程序会呈现视图,我已经将内容更改为 exceptions/handler.php 我选择创建一个返回 jason 的自定义异常并且有效!
【解决方案2】:

throw new GeneralException('invalid required extra quantity');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-01
    • 2017-12-21
    • 2015-03-18
    • 2019-02-22
    • 1970-01-01
    • 2018-10-03
    • 2014-06-25
    • 2018-08-29
    相关资源
    最近更新 更多