protected function registerFatalHandler()
    {
        $error = $this;

        // When shutdown, the current working directory will be set to the web
        // server directory, store it for later use
        $cwd = getcwd();

        register_shutdown_function(function () use ($error, $cwd) {
            $e = error_get_last();
            if (!$e || !in_array($e['type'], array(E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE))) {
                // No error or not fatal error
                return;
            }

            ob_get_length() && ob_end_clean();

            // Reset the current working directory to make sure everything work as usual
            chdir($cwd);

            $exception = new \ErrorException($e['message'], $e['type'], 0, $e['file'], $e['line']);

            if ($error->triggerHandler('fatal', $exception)) {
                // Handled!
                return;
            }

            // Fallback to error handlers
            if ($error->triggerHandler('error', $exception)) {
                // Handled!
                return;
            }

            // Fallback to internal error Handlers
            $error->internalHandleException($exception);
        });
    }