<?php

namespace App\Error;

use Cake\Error\ExceptionRenderer;
use Cake\Http\Exception\NotFoundException;
use Cake\Routing\Exception\MissingControllerException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Controller\Exception\MissingActionException;

class AppExceptionRenderer extends ExceptionRenderer
{
    public function render()
    {
        // Handle missing controller or other not found errors
        if (
            $this->error instanceof MissingControllerException ||
            $this->error instanceof NotFoundException ||
            $this->error instanceof MissingTemplateException||
            $this->error instanceof MissingActionException
        ) {
            return $this->_renderCustom404();
        }

        return parent::render();
    }

    protected function _renderCustom404()
    {
        $this->controller->response = $this->controller->response->withStatus(404);

        $this->controller->viewBuilder()
            ->layout(false)
            ->templatePath('Error')
            ->template('custom_404');

        return $this->_outputMessage('custom_404');
    }
}