Laravel abort() 与返回 response()->json()

Moh*_*mar 2 laravel

在 Laravel 中,abort()和之间有什么区别response()->json()

例如:

return response()->json(['message' => 'Not found'], 404);
Run Code Online (Sandbox Code Playgroud)

和:

abort(404, 'Not found');
Run Code Online (Sandbox Code Playgroud)

编辑:我认为abort()不会抛出一个异常,如果APP_DEBUGfalse.env文件中。

这是我的代码:

protected function prepareForValidation()
{
    $this->replace(array_filter($this->all()));

    if(!$this->all()) {
        abort(422, 'You must edit something.');
    }
}
Run Code Online (Sandbox Code Playgroud)

如果请求中的所有字段都为空,如果我使用它立即停止执行并返回消息(在开始验证之前)是否有问题?

emo*_*ity 7

response()->json(['message' => 'not found'], 404);

不会抛出异常,异常处理程序也不会处理它,它会简单地返回一个404带有您的响应的状态代码。


abort(404, 'not found');

将抛出NotFoundHttpException()异常并将由位于以下位置的异常处理程序处理:app/Exceptions/Handler.php


请参阅以下功能abort()

public function abort($code, $message = '', array $headers = [])
{
    if ($code == 404) {
        throw new NotFoundHttpException($message);
    }

    throw new HttpException($code, $message, null, $headers);
}
Run Code Online (Sandbox Code Playgroud)

正如您在上面看到的,该abort()函数总是抛出异常。如果APP_DEBUGfalse,您将不会看到异常详细信息,但它会被记录到您的logs文件夹中。

  • 感谢您的澄清。现在我可以在事务中安全地使用 abort 了,知道它不会使用某些 php 本机函数来终止进程,但它只会抛出一个异常,每当执行 abort 时,它就会允许 DB:transaction 函数执行角色返回操作! (2认同)