Ros*_*fri 9 php laravel laravel-8
当ModelNotFoundException发生时,我想返回一个 JSON 响应而不是默认的 404 错误页面。为此,我将以下代码写入app\Exceptions\Handler.php:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Resource not found'
], 404);
}
return parent::render($request, $exception);
}
Run Code Online (Sandbox Code Playgroud)
但是它不起作用。当ModelNotFoundException发生时,Laravel 只显示一个空白页面。我发现,即使是在宣告一个空的渲染功能Handler.php品牌Laravel上显示空白页ModelNotFoundException。
我该如何解决这个问题,以便它可以返回 JSON/执行覆盖渲染函数中的逻辑?
Dil*_*ara 14
在 Laravel 8x 中,你需要Rendering Exceptions在register()方法中
use App\Exceptions\CustomException;
/**
* Register the exception handling callbacks for the application.
*
* @return void
*/
public function register()
{
$this->renderable(function (CustomException $e, $request) {
return response()->view('errors.custom', [], 500);
});
}
Run Code Online (Sandbox Code Playgroud)
因为ModelNotFoundException您可以按如下方式进行。
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
return response()->json(...);
});
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,Laravel 异常处理程序会为您将异常转换为 HTTP 响应。但是,您可以自由地为给定类型的异常注册自定义渲染闭包。您可以通过renderable异常处理程序的方法完成此操作。Laravel 将通过检查闭包的类型提示来推断闭包呈现的异常类型:
有关错误异常的更多信息
这段代码对我不起作用(在 Laravel 8.74.0 中):
$this->renderable(function (ModelNotFoundException$e, $request) {
return response()->json(...);
});
Run Code Online (Sandbox Code Playgroud)
不知道为什么,但ModelNotFoundException直接转发到Laravel 使用的(这是Symfony 组件NotFoundHttpException的一部分),最终会触发 404 HTTP 响应。我的解决方法是检查异常的方法:getPrevious()
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
if ($e->getPrevious() instanceof ModelNotFoundException) {
return response()->json([
'status' => 204,
'message' => 'Data not found'
], 200);
}
return response()->json([
'status' => 404,
'message' => 'Target not found'
], 404);
}
});
Run Code Online (Sandbox Code Playgroud)
然后我们就会知道这个异常来自ModelNotFoundException并返回不同的响应NotFoundHttpException。
编辑
这就是为什么ModelNotFoundException抛出NotFoundHttpException
| 归档时间: |
|
| 查看次数: |
5043 次 |
| 最近记录: |