I'll-Be-Back
I'll-Be-Back

Reputation: 10838

json response via exception

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?

Upvotes: 0

Views: 383

Answers (1)

user320487
user320487

Reputation:

You could bind an error type and error code identifier to the app container and have it create the correct exception class. For example:

app()->bind('type1-error1', ExceptionClass1::class);
app()->bind('type2-error2', ExceptionClass2::class);
app()->bind('type2-error3', ExceptionClass3::class);

These could be bound early in the application life cycle such as in AppServiceProvider boot(). Then the exception handler could resolve an instance of the correct exception based on the type-error combination using:

$e = app('type1-error1');
throw $e;

The container is a powerful tool at your disposal!

Upvotes: 1

Related Questions