Improved the way rest errors are catched

This commit is contained in:
Alejandro Celaya 2016-07-26 11:05:17 +02:00
parent 0ef1e416c6
commit 83f29080c6
2 changed files with 41 additions and 7 deletions

View file

@ -45,15 +45,48 @@ class ResponseTypeMiddleware implements ErrorMiddlewareInterface
{
$accept = $request->getHeader('Accept');
if (! empty(array_intersect(['application/json', 'text/json', 'application/x-json'], $accept))) {
$status = $response->getStatusCode();
$status = $status >= 400 ? $status : 500;
$status = $this->determineStatus($response);
$errorData = $this->determineErrorCode($request, $status);
return new JsonResponse([
'error' => RestUtils::UNKNOWN_ERROR,
'message' => $this->translator->translate('Unknown error'),
], $status);
return new JsonResponse($errorData, $status);
}
return $out($request, $response, $error);
}
/**
* @param Response $response
* @return int
*/
protected function determineStatus(Response $response)
{
$status = $response->getStatusCode();
return $status >= 400 ? $status : 500;
}
/**
* @param Request $request
* @param int $status
* @return string
*/
protected function determineErrorCode(Request $request, $status)
{
$errorData = $request->getAttribute('errorData');
if (isset($errorData)) {
return $errorData;
}
switch ($status) {
case 404:
return [
'error' => RestUtils::NOT_FOUND_ERROR,
'message' => $this->translator->translate('Requested route does not exist'),
];
default:
return [
'error' => RestUtils::UNKNOWN_ERROR,
'message' => $this->translator->translate('Unknown error occured'),
];
}
}
}

View file

@ -11,7 +11,8 @@ class RestUtils
const INVALID_URL_ERROR = 'INVALID_URL';
const INVALID_ARGUMENT_ERROR = 'INVALID_ARGUMENT';
const INVALID_CREDENTIALS_ERROR = 'INVALID_CREDENTIALS';
const INVALID_AUTH_TOKEN_ERROR = 'INVALID_AUTH_TOKEN_ERROR';
const INVALID_AUTH_TOKEN_ERROR = 'INVALID_AUTH_TOKEN';
const NOT_FOUND_ERROR = 'NOT_FOUND';
const UNKNOWN_ERROR = 'UNKNOWN_ERROR';
public static function getRestErrorCodeFromException(Common\ExceptionInterface $e)