I have created a worker class in Laravel.
The worker class communicate to with Lumen. If there is an error in Lumen it will response back in json to Laravel.
The worker class like this:-
class Worker {
public function put($ip, $user, $file)
{
try {
$response = $this->client->post('/put', ['form_params' => ['ip' => $ip,'username' => $user, 'file' => $file]]);
$responseBody = (string)$response->getBody();
// do something
} catch (ClientException | ServerException $e) {
return $this->handleRequestError($e);
}
}
protected function handleRequestError($e)
{
if ($e instanceof ClientException) {
if ($e->getCode() == 422) {
throw new WorkerValidationException((string)$e->getResponse()->getBody());
}
}
if ($e instanceof ServerException) {
$error = json_decode($e->getResponse()->getBody(), true);
if ($error['error_type'] == 'ftp') {
throw new FtpException((string)$e->getResponse()->getBody());
}
if ($error['error_type'] == 'somethingElse') {
throw new SomethingElseException((string)$e->getResponse()->getBody());
}
}
throw new \Exception((string) $e->getResponse()->getBody());
}
}
The handleRequestError() method read the value of $error['error_type'] and throw specific exception.
However, I want 2 or 3 error codes ($error['code']) to response back to the user with json format. What is good approach to do this?
Eg:
if (if ($error['error_type'] == 'ftp' && $error['code'] == 200) {
response(['success' => false, 'message' => 'could not connect']);
}
I don't want to put response logic in the worker class. Do I need to do it in Exception Handler?