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);
}