Always validate database query results before accessing their methods or properties. Methods like `findOne()`, `getDocument()`, and similar database operations can return null or empty documents. Failing to check these results before access leads to runtime errors.
Always validate database query results before accessing their methods or properties. Methods like findOne()
, getDocument()
, and similar database operations can return null or empty documents. Failing to check these results before access leads to runtime errors.
Example of unsafe code:
$latestDeployment = $dbForProject->findOne('deployments', [ /* ... */ ]);
$latestBuild = $dbForProject->getDocument('builds',
$latestDeployment->getAttribute('buildId', '') // May throw if $latestDeployment is null
);
Safe pattern:
$latestDeployment = $dbForProject->findOne('deployments', [ /* ... */ ])
?? new Document(); // Provide empty fallback
if (!$latestDeployment->isEmpty()) { // Check before accessing
try {
$latestBuild = $dbForProject->getDocument(
'builds',
$latestDeployment->getAttribute('buildId', '')
);
} catch (Throwable $e) {
$latestBuild = new Document(); // Handle failure gracefully
}
}
Key practices:
Enter the URL of a public GitHub repository