Skip to content

transprime-research/attempt

Repository files navigation

Build Status Latest Stable Version Total Downloads Latest Unstable Version Latest Monthly Downloads License

About Attempt

Try and catch in php objected oriented way

Do It like a pro 🆗

Usage

$response = attempt(fn() => $this->client->get('ninja'))
    ->catch(ConnectException::class)
    ->done(fn() => []); //done can be replaced with ()

Installation:

Minimum requirement is PHP 7.2+ and Composer.

Install with this:

composer require transprime-research/attempt

Other usage:

$response = Attempt::on(fn() => $this->client->get('ninja'))
    ->catch(AttemptTestException::class)(); // or ->done()

// Do something with Response

catch method accepts an Exception object:

$response = Attempt::on(fn() => $this->client->get('ninja'))
    ->catch(\AttemptTestException())(); // or ->done()

// Do something with Response

Set a default response:

$response = Attempt::on(fn() => $this->client->get('ninja'))
    ->with(['abc'])
    ->catch(AttemptTestException::class)
    ->done(); // ['abc'] is returned if exception is caught  
// with default value
attempt(fn() => $this->execute())
    ->catch(AttemptTestException::class, 'It is done') //returns 'It is done'
    ->done();
    
// closure as default value
attempt(fn() => $this->execute())
    ->catch(AttemptTestException::class, fn() => 'It is done') //returns 'It is done'
    ->done();
    
// handle the resolved default value in done()
attempt(fn() => $this->execute())
    ->catch(AttemptTestException::class, fn() => 'error') //returns 'It is done'
    ->done(fn(Exception $ex, $severity) => logger($severity, $ex));

Multiple Exception

$response = Attempt::on(fn() => $this->client->get('ninja'))
    ->catch(AttemptTestException::class, HttpResponseException::class)()

// Do something with Response

Multiple Catch block

attempt(fn() => $this->execute())
    ->catch(NinjaException::class, 'Ninja error') //returns 'It is done')
    ->catch(AnotherExeption::class, 'Another error') //returns 'It is done'
    ->done(fn($ex) => logger()->error($ex));

Do more with the caught Exception response:

$response = Attempt::on(fn() => $this->client->get('ninja'))
    ->catch(AttemptTestException::class, HttpResponseException::class)
    ->done(fn(\HttpResponseException $e) => logger()->error($e->getMessage()));

// Do something with Response

More to come: Pass the execution of a default value to a callable Class

// loading...

Additional Information

This package is part of a series of "The Code Dare".

See other packages in this series here:

Similar packages

  • TBA

Licence

MIT (See LICENCE file)