2016-12-15 10:13:00 +01:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace Shaarli\Api\Exceptions;
|
|
|
|
|
|
|
|
use Slim\Http\Response;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Abstract class ApiException
|
|
|
|
*
|
|
|
|
* Parent Exception related to the API, able to generate a valid Response (ResponseInterface).
|
|
|
|
* Also can include various information in debug mode.
|
|
|
|
*/
|
2018-10-13 00:19:03 +02:00
|
|
|
abstract class ApiException extends \Exception
|
|
|
|
{
|
2016-12-15 10:13:00 +01:00
|
|
|
/**
|
|
|
|
* @var Response instance from Slim.
|
|
|
|
*/
|
|
|
|
protected $response;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @var bool Debug mode enabled/disabled.
|
|
|
|
*/
|
|
|
|
protected $debug;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build the final response.
|
|
|
|
*
|
|
|
|
* @return Response Final response to give.
|
|
|
|
*/
|
2018-10-13 00:19:03 +02:00
|
|
|
abstract public function getApiResponse();
|
2016-12-15 10:13:00 +01:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Creates ApiResponse body.
|
|
|
|
* In production mode, it will only return the exception message,
|
|
|
|
* but in dev mode, it includes additional information in an array.
|
|
|
|
*
|
|
|
|
* @return array|string response body
|
|
|
|
*/
|
2018-10-13 00:19:03 +02:00
|
|
|
protected function getApiResponseBody()
|
|
|
|
{
|
2016-12-15 10:13:00 +01:00
|
|
|
if ($this->debug !== true) {
|
|
|
|
return $this->getMessage();
|
|
|
|
}
|
|
|
|
return [
|
|
|
|
'message' => $this->getMessage(),
|
2023-05-24 11:35:15 +02:00
|
|
|
'stacktrace' => get_class($this) . ': ' . $this->getTraceAsString()
|
2016-12-15 10:13:00 +01:00
|
|
|
];
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Build the Response object to return.
|
|
|
|
*
|
|
|
|
* @param int $code HTTP status.
|
|
|
|
*
|
|
|
|
* @return Response with status + body.
|
|
|
|
*/
|
|
|
|
protected function buildApiResponse($code)
|
|
|
|
{
|
|
|
|
$style = $this->debug ? JSON_PRETTY_PRINT : null;
|
|
|
|
return $this->response->withJson($this->getApiResponseBody(), $code, $style);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param Response $response
|
|
|
|
*/
|
|
|
|
public function setResponse($response)
|
|
|
|
{
|
|
|
|
$this->response = $response;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param bool $debug
|
|
|
|
*/
|
|
|
|
public function setDebug($debug)
|
|
|
|
{
|
|
|
|
$this->debug = $debug;
|
|
|
|
}
|
|
|
|
}
|