I have added a custom error handler to my backend. However, I am getting 500 Internal Server Error.
Here’s my code:
$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);
$app->addRoutingMiddleware();
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, $logErrors, $logErrorDetails);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);
My HttpErrorHandler
class HttpErrorHandler extends ErrorHandler
{
public const BAD_REQUEST = ‘BAD_REQUEST’;
public const INSUFFICIENT_PRIVILEGES = ‘INSUFFICIENT_PRIVILEGES’;
public const NOT_ALLOWED = ‘NOT_ALLOWED’;
public const NOT_IMPLEMENTED = ‘NOT_IMPLEMENTED’;
public const RESOURCE_NOT_FOUND = ‘RESOURCE_NOT_FOUND’;
public const SERVER_ERROR = ‘SERVER_ERROR’;
public const UNAUTHENTICATED = ‘UNAUTHENTICATED’;
protected function logError(string $error): void
{
//TODO
// Insert custom error logging function.
}
protected function respond(): ResponseInterface
{
$exception = $this->exception;
$statusCode = 500;
$type = self::SERVER_ERROR;
$description = 'An internal error has occurred while processing your request.';
if ($exception instanceof HttpException) {
$statusCode = $exception->getCode();
$description = $exception->getMessage();
if ($exception instanceof HttpNotFoundException) {
$type = self::RESOURCE_NOT_FOUND;
} elseif ($exception instanceof HttpMethodNotAllowedException) {
$type = self::NOT_ALLOWED;
} elseif ($exception instanceof HttpUnauthorizedException) {
$type = self::UNAUTHENTICATED;
} elseif ($exception instanceof HttpForbiddenException) {
$type = self::UNAUTHENTICATED;
} elseif ($exception instanceof HttpBadRequestException) {
$type = self::BAD_REQUEST;
} elseif ($exception instanceof HttpNotImplementedException) {
$type = self::NOT_IMPLEMENTED;
}
}
if (
!($exception instanceof HttpException)
&& ($exception instanceof Exception || $exception instanceof Throwable)
&& $this->displayErrorDetails
) {
$description = $exception->getMessage();
}
$error = [
'statusCode' => $statusCode,
'error' => [
'type' => $type,
'description' => $description,
],
];
$payload = json_encode($error, JSON_PRETTY_PRINT);
$response = $this->responseFactory->createResponse($statusCode);
$response->getBody()->write($payload);
return $response;
}
}
What am I doing wrong?
My requirement here is pretty simple: Everytime there’s an error (404, 500 or similar), I want to render a common web page with different status code and message each time. I couldn’t figure out how to catch those errors automatically.