dimanche 9 juillet 2017

Improving handleRequestError and handler()?

I have created a worker class in Laravel.

The put() will attempt to communicate with a service provider and if there is an error, it will be thrown to handleRequestError() method

The handleRequestError() method read the value of $error['error_type'] and throw specific exception.

The Handler.php will catch it and response back to user in json.

Is there a way to improve handleRequestError() code and refactoring?

The worker class look 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'] == 'sftp') {
                throw new SftpException((string)$e->getResponse()->getBody());
            }
        }


        throw new \Exception((string) $e->getResponse()->getBody());
    }
}

In the Handler.php

public function render($request, Exception $exception)
{

    if ($exception instanceof FtpException) {
        $error = json_decode($exception->getMessage(), true);

        if ($error['error']['code'] == 100)
        {
            return response()->json(['error' => ['message' => 'Unable to login']], 405);
        }
    }

    return parent::render($request, $exception);
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2twdJ7L
via IFTTT

Aucun commentaire:

Enregistrer un commentaire