私はLaravelでワーカークラスを作成しました。例外によるjson応答
作業員クラスはルーメンと通信します。 Lumenにエラーがある場合、Laravelにjsonで応答します。
このような労働者階級: -
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());
}
}
handleRequestError()
方法$error['error_type']
の値を読み、特定の例外をスローします。
しかし、私はjson形式のユーザーに応答するために2つまたは3つのエラーコード($error['code']
)が必要です。これを行うための良いアプローチは何ですか?
例:
if (if ($error['error_type'] == 'ftp' && $error['code'] == 200) {
response(['success' => false, 'message' => 'could not connect']);
}
私は労働者のクラスに応答ロジックを置きたくはありません。私は例外ハンドラでそれを行う必要がありますか?
ワーカークラスはよく見えますが、常に例外をスローする必要があります。呼び出し元関数は、どの例外が発生するか、正常に処理するものを決定する必要があります。 –