I have a problem with the flow of error handling. I have a try and catch block, and I need to ensure that the try block contains the logic for what should be executed. Specifically, a ticket should be created. However, the creation of the ticket can fail for two reasons. The first reason is that it cannot find the responder_id, which means either it doesn’t exist or it is working with a responder_id that is no longer in the database. In this case, I need to create a new ticket but set the responder_id to null, which I have implemented and it works.
My issue is with throwing errors. I need to ensure that the try-catch block can throw two types of errors. The first one should be thrown if the failure is due to an invalid responder_id, and the second one should be a general error if the ticket creation fails for any other reason. When I throw an exception only in the catch block, the exception is not thrown even though it is clearly dealing with an invalid responder_id.
I’ve gotten a bit lost and can’t figure out how to do it correctly. Could anyone please offer some advice?
This is code
if ($agent = $this->getAgent()) {
$data["responder_id"] = $agent;
}
try {
$response = FreshdeskService::createTicket($data, $this->getTo(), $attachments);
$success = $response["success"] ?? false;
if (!$success) {
$error_response = json_decode($response['response'], true);
$error_details = $error_response['errors'] ?? [];
foreach ($error_details as $error) {
if ($error['field'] === 'responder_id') {
}
}
throw new Exception("Create ticket failed due to invalid responder_id: " . $this->getAgent() . ". Error details: " . json_encode($error_details));
}
} catch (Exception $e) {
$data['responder_id'] = null;
$response = FreshdeskService::createTicket($data, $this->getTo(), $attachments);
Log::info($response);
$success = $response["success"] ?? false;
if (!$success) {
throw new Exception("Retry ticket creation failed: From: " . $this->getFrom() . ", To: " . $this->getTo() . ", Subject: " . $this->subject . ", Response: " . json_encode($response["response"] ?? []) . ", Data: " . json_encode($data));
}
throw new Exception($e->getMessage());
}
I hope this post will find someone who can give me some advice about this problem.