Last active
November 11, 2019 12:45
-
-
Save kobus1998/10411154dcd42ac77421a760872357e4 to your computer and use it in GitHub Desktop.
automatic api error response
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// placeholder | |
class Response | |
{ | |
} | |
class ApiError extends \Exception | |
{ | |
protected static $errorCodes = [ | |
1 => 'something went wrong or whatever' | |
]; | |
public function __construct(Response $response, $type, $code) | |
{ | |
$this->response = $response; | |
$this->type = $type; | |
$this->code = $code; | |
$this->message = self::$errorCodes[$code]; | |
parent::__construct("{$this->type}: {$this->message}", $this->code); | |
$this->response(); | |
} | |
public function response() | |
{ | |
$this->response | |
->setHeader('content-type', 'application/json') | |
->json([ | |
'errors' => [ | |
[ | |
'type' => $this->type, | |
'code' => $this->code, | |
'message' => $this->message | |
] | |
] | |
]) | |
->handle(); | |
} | |
} | |
try { | |
throw new ApiError(new Response(), 'user', 1); | |
} catch (\Exception $e) {} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment