diff --git a/module/Rest/src/Middleware/Error/ResponseTypeMiddleware.php b/module/Rest/src/Middleware/Error/ResponseTypeMiddleware.php index a7e2c5e8..c6319caa 100644 --- a/module/Rest/src/Middleware/Error/ResponseTypeMiddleware.php +++ b/module/Rest/src/Middleware/Error/ResponseTypeMiddleware.php @@ -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'), + ]; + } + } } diff --git a/module/Rest/src/Util/RestUtils.php b/module/Rest/src/Util/RestUtils.php index 8e50a1cf..b67491ed 100644 --- a/module/Rest/src/Util/RestUtils.php +++ b/module/Rest/src/Util/RestUtils.php @@ -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)