Amarjit Singh
Amarjit Singh

Reputation: 2154

laravel unable to handle exception, catch block not executing

I am on my way to creating an SSH Bot that performs various operations on the remote servers. The username and passwords for these servers are provided by the user.

But when the user provides wrong username or password or a wrong IP address of the server then it throws ErrorException exception.

I want to handle that exception and store error message in the database. Instead of showing it to the user.

here is my code

try {
                $pending_server->console_output = $this->setupDNS($pending_server->toArray());
                $pending_server->status = 'Configured';
            } catch (ErrorException $e) {
                $pending_server->console_output = $e->getMessage;
                $pending_server->status = 'Failed';
                $pending_server->save();
            }

In the database $pending_server is the database model. The setupDNS method is throwing the exception. Therefore in case of an exception, I want to store the error message as the output in the database. But the catch block is not executing at all and execution of script stops.

Upvotes: 2

Views: 294

Answers (1)

Satinderpal Singh
Satinderpal Singh

Reputation: 548

just put '\' before ErrorException. For eg:

try {
                $pending_server->console_output = $this->setupDNS($pending_server->toArray());
                $pending_server->status = 'Configured';
            } catch (\ErrorException $e) {
                $pending_server->console_output = $e->getMessage;
                $pending_server->status = 'Failed';
                $pending_server->save();
            }

Upvotes: 2

Related Questions