0

I'd like to create something similar to the unauthenticated() function in

app\Exceptions\Handler.php

But my exception is one generated by Guzzle containing a certain http code and json body.

I already have a helper class that would work like this:

  public static function get($enum) {
        $headers = self::headers();
        $client = new Client();
        try {
            $response = $client->request('GET', config('app.apiurl') . '/api/' . $enum, ['headers' => $headers]);
        } catch (\Exception $e) {
            $response = $e->getResponse();
            $body = json_decode($response->getBody(), true);
            $code = $response->getStatusCode();

           if ($body['code'] == 101 && $code == 412) {
               throw new \Exception("wizard eerst", 101);
           }
        }

But I prefer to do this in a universal handler like some kind of middleware for exceptions. So I'd like to NOT use a try catch every call, but catch all exceptions that fit my description and handle them with a redirect.

Solution

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

$response = $exception->getResponse();
$body = json_decode($response->getBody(), true);
$code = $response->getStatusCode();

if ($body['code'] == 101 && $code == 412) {
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Je moet eerst de profielwizard afmaken'], $code);
    }

    return redirect('/wizard');
}

return parent::render($request, $exception);
}
online Thomas
  • 8,864
  • 6
  • 44
  • 85
  • Possible duplicate of [Catching exceptions from Guzzle](http://stackoverflow.com/questions/17658283/catching-exceptions-from-guzzle) – GiamPy Feb 03 '17 at 15:50
  • @GiamPy It's not, I described that I would like to handle it another way and I already succesfully have implemented this way. – online Thomas Feb 03 '17 at 15:51

1 Answers1

0

There exists a render function in app\Exceptions\Handler.php.

To deal with different types of Exception, you can try:

public function render($request, Exception $e)
{
    if ($e instanceof SomeTypeException1)
    {
        #handle it
    }
    else if($e instanceof SomeTypeException2)
    {
        #handle it
    }

    return parent::render($request, $e);
}
William wei
  • 261
  • 2
  • 12