HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/farmfun.komma.pro/app/Komma/Teamleader/Base/ApiException.php
<?php

namespace App\Komma\Teamleader\Base;

use GuzzleHttp\Psr7\Response;

class ApiException extends \Exception
{
    /** @var Response */
    protected $response;

    /** @var object */
    protected ?object $body;

    /**
     * ApiException constructor.
     * @param Response $response
     * @param ?object $body
     * @throws \Exception
     */
    public function __construct(Response $response, object $body = null)
    {
        $this->response = $response;
        $this->body = $body;

        parent::__construct($this->createMessageFromBody($body), $response->getStatusCode());
    }

    /**
     * Get the error message
     *
     * @param ?object $body
     * @return string
     */
    private function createMessageFromBody(object $body = null)
    {
        $message = 'Error executing API call';

        if (! isset($body)) {
            return $message;
        }

//        if(config('app.debug')) dd($body);

        if (isset($body) && isset($body->errors)) {
            foreach ($body->errors as $error) {
                $message .= ' | '.$error->title;
                debug($error);
            }
        }

        if (isset($body->details)) {
            if (isset($body->details->message) && is_string($body->details->message)) {
                return $message .= ' ('.$body->details->message.')';
            }
        }

        if (isset($body->message) && is_string($body->message)) {
            return $message .= ' ('.$body->message.')';
        }

        return $message;
    }

    /**
     * Get the body of the API response
     *
     * @return object
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Convert ApiException into a Json Response
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function response(): \Illuminate\Http\JsonResponse
    {
        return response()->json([
            'status' => $this->getCode(),
            'statusText' => $this->getMessage(),
            'data' => $this->getBody(),
        ], $this->getCode());
    }
}