Failing Laravel Jobs
Reviewing a PR today that used both Jobs and Actions. There was an issue where if the HTTP request in the Action failed the Job itself would not fail.
The Job would still return as green even though the Job was technically unsuccessful. This was happening because, even though this request was wrapped
in a try catch
block, the developer was only logging the response if it was unsuccessful
// SendDataJob.php
public function handle()
{
try {
app(SendData::class)($this->data);
} catch (Exception $e) {
Log::error('Failed to send data', [
'order' => $this->data,
'error' => $e->getMessage(),
]);
throw $e;
}
}
// SendData.php
public function __invoke(array $postData)
{
try {
$username = config('username');
$password = config('password');
$apiUrl = config('api_url');
$response = Http::withBasicAuth($username, $password)->post($apiUrl, $postData);
if ($response->successful()) {
Log::info('Request Successful');
} else {
Log::error('Request Failed', ['response' => $response->body()]);
} } catch (Exception $e) {
Log::error('Failed to send data', [
'order' => $postData,
'error' => $e->getMessage(),
]);
}
}
My recommendation was to remove the try catch
block from the Action and add
thethrow
methodonto the request.
Http::withBasicAuth($username, $password)->post($apiUrl, $ebmsOrder)->throw();
This way if the response is either a 400 or 500 level error, an exception will be thrown which will bubble up to the Job and fail the Job.