Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active November 11, 2019 12:45
Show Gist options
  • Save kobus1998/10411154dcd42ac77421a760872357e4 to your computer and use it in GitHub Desktop.
Save kobus1998/10411154dcd42ac77421a760872357e4 to your computer and use it in GitHub Desktop.
automatic api error response
<?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