Skip to content

Commit

Permalink
ServerErrorException: allow change the default message
Browse files Browse the repository at this point in the history
  • Loading branch information
mabar authored and f3l1x committed Sep 24, 2019
1 parent abc0a55 commit 43f6fde
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 4 deletions.
3 changes: 2 additions & 1 deletion src/ErrorHandler/SimpleErrorHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Apitte\Core\ErrorHandler;

use Apitte\Core\Exception\Api\ServerErrorException;
use Apitte\Core\Exception\ApiException;
use Apitte\Core\Exception\Runtime\SnapshotException;
use Apitte\Core\Http\ApiResponse;
Expand Down Expand Up @@ -49,7 +50,7 @@ protected function createResponseFromError(Throwable $error): ApiResponse
$data = [
'status' => 'error',
'code' => $code,
'message' => $error instanceof ApiException ? $error->getMessage() : 'Application encountered an internal error. Please try again later.',
'message' => $error instanceof ApiException ? $error->getMessage() : ServerErrorException::$defaultMessage,
];

if ($error instanceof ApiException && ($context = $error->getContext()) !== null) {
Expand Down
7 changes: 5 additions & 2 deletions src/Exception/Api/ServerErrorException.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,16 @@
class ServerErrorException extends ApiException
{

public function __construct(string $message = 'Application encountered an internal error. Please try again later.', int $code = 500, ?Throwable $previous = null)
/** @var string */
public static $defaultMessage = 'Application encountered an internal error. Please try again later.';

public function __construct(string $message = '', int $code = 500, ?Throwable $previous = null)
{
if ($code < 500 || $code > 599) {
throw new InvalidArgumentException(sprintf('%s code could be only in range from 500 to 599', static::class));
}

parent::__construct($message, $code, $previous);
parent::__construct($message !== '' ? $message : static::$defaultMessage, $code, $previous);
}

}
3 changes: 2 additions & 1 deletion tests/cases/ErrorHandler/SimpleErrorHandler.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use Apitte\Core\ErrorHandler\SimpleErrorHandler;
use Apitte\Core\Exception\Api\ClientErrorException;
use Apitte\Core\Exception\Api\ServerErrorException;
use Apitte\Core\Exception\Runtime\SnapshotException;
use Apitte\Core\Http\ApiRequest;
use Apitte\Core\Http\ApiResponse;
Expand Down Expand Up @@ -36,7 +37,7 @@ test(function (): void {
[
'status' => 'error',
'code' => 500,
'message' => 'Application encountered an internal error. Please try again later.',
'message' => ServerErrorException::$defaultMessage,
],
$response->getJsonBody()
);
Expand Down

0 comments on commit 43f6fde

Please sign in to comment.