在 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_DEBUG是false在.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)
如果请求中的所有字段都为空,如果我使用它立即停止执行并返回消息(在开始验证之前)是否有问题?
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_DEBUG是false,您将不会看到异常详细信息,但它会被记录到您的logs文件夹中。
| 归档时间: |
|
| 查看次数: |
4256 次 |
| 最近记录: |