Gets a suitable WebSocket close frame.
Please set `masked` to false if you send a close frame from server side.

@param Exception|int $e
@param boolean       $masked
@return Payload
775292
public function getClosePayload($e, $masked = true)
    {
        $code = false;

        if ($e instanceof Exception) {
            $code = $e->getCode();
        } elseif (is_numeric($e)) {
            $code = (int)$e;
        }

        if (!$code || !key_exists($code, self::CLOSE_REASONS)) {
            $code = self::CLOSE_UNEXPECTED;
        }

        $body = pack('n', $code) . self::CLOSE_REASONS[$code];

        $payload = $this->getPayload();
        return $payload->encode($body, self::TYPE_CLOSE, $masked);
    }
1198191
public function unmaskToken($maskedToken)
	{
		$decoded=base64_decode(strtr($maskedToken,'-_','+/'));
		$length=$this->strlen($decoded)/2;
		// Check if the masked token has an even length.
		if(!is_int($length))
			return '';
		return $this->substr($decoded,$length,$length)^$this->substr($decoded,0,$length);
	}
341276
protected function handleClientCloseFrame(NetworkFrame $frame)
    {
        $this->logger->debug("Client sent close frame, parsing");

        //TODO strict
        $code = $frame->getPayloadPart(0, 2);

        if (!empty($code)) { //Code is optional BUT it can't be 0
            if (!isset($code[1])) { // payload have to be at least 2 bytes
                throw new WebSocketException("Invalid closing payload", DataFrame::CODE_PROTOCOL_ERROR);
            }

            $code = unpack("n", $code);
            $code = $code[1]; //Array dereference on call is allowed from 5.4
            $this->logger->debug("Client disconnected with code: " . $code);

            if (!DataFrame::validateCloseCode($code)) {
                throw new WebSocketException("Invalid close code", DataFrame::CODE_PROTOCOL_ERROR);
            }

            if (!mb_check_encoding($frame->getPayloadPart(2), 'UTF-8')) {
                throw new WebSocketException("Close frame payload is not valid UTF-8",
                    NetworkFrame::CODE_DATA_TYPE_INCONSISTENT);
            }
        }

        $this->logger->debug("Converting client close frame into server close frame");
        $frame->setOpcode(DataFrame::OPCODE_CLOSE);
        $frame->setMasking(false);
        $frame->setPayload(pack("n", DataFrame::CODE_CLOSE_NORMAL) . "Client closed connection");
        $this->pushData($frame);
        $this->disconnect();
    }
875700
public function handleWsError($e)
    {
        // Pawl pls
        if (strpos($e->getMessage(), 'Tried to write to closed stream') !== false) {
            return;
        }

        $this->logger->error('websocket error', ['e' => $e->getMessage()]);
        $this->emit('error', [$e, $this]);

        $this->handleWsClose(0, 'websocket error');
    }
787510
protected function renderException(Request $request, Exception $e)
    {
        return $this->app['Nano7\Foundation\Contracts\Exception\ExceptionHandler']->render($request, $e);
    }
63597
public static function wrap(RequestException $e)
    {
        $response = $e->getResponse();

        if ($errors = self::errors($response)) {
            $class = self::exceptionClass($response, $errors[0]);
            $message = implode(', ', array_map('strval', $errors));
        } else {
            $class = self::exceptionClass($response);
            $message = $e->getMessage();
        }

        return new $class($message, $errors, $e->getRequest(), $response, $e);
    }
628133
public static function decode($buffer, ConnectionInterface $connection)
    {
        $masks = $data = $decoded = '';
        $len = ord($buffer[1]) & 127;
        if ($len === 126) {
            $masks = substr($buffer, 4, 4);
            $data  = substr($buffer, 8);
        } else {
            if ($len === 127) {
                $masks = substr($buffer, 10, 4);
                $data  = substr($buffer, 14);
            } else {
                $masks = substr($buffer, 2, 4);
                $data  = substr($buffer, 6);
            }
        }
        for ($index = 0; $index < strlen($data); $index++) {
            $decoded .= $data[$index] ^ $masks[$index % 4];
        }
        if ($connection->websocketCurrentFrameLength) {
            $connection->websocketDataBuffer .= $decoded;
            return $connection->websocketDataBuffer;
        } else {
            if ($connection->websocketDataBuffer !== '') {
                $decoded                         = $connection->websocketDataBuffer . $decoded;
                $connection->websocketDataBuffer = '';
            }
            return $decoded;
        }
    }
596032
public function getMessageViaDefault(Exception $e)
    {
        $msg = get_class($e)." was thrown! \n".$e->getMessage();
        if ($this->config['includeExceptionStackTrace'] === true) {
            $msg .= "\n\n".$e->getTraceAsString();
        }
        return $msg;
    }
930618
protected function convertExceptionToResponse(Exception $e, Request $request)
    {
        $debug = Config::get('app.debug');

        //
        $e = FlattenException::create($e);

        $handler = new SymfonyExceptionHandler($debug);

        return SymfonyResponse::create($handler->getHtml($e), $e->getStatusCode(), $e->getHeaders());
    }
337700
private function getExceptionStackTrace(\Exception $e, $html = true)
    {
        $wrap = ($html) ? ['<b>', '</b>'] : ['', ''];
        $bold = function ($s) use ($wrap) { return implode($s, $wrap); };

        $newLine = ($html) ? '<br>' : "\n";

        $trace = $bold('Error Time :').date('Y-m-d H:i:s A');
        $trace .= $newLine.$bold('Error Code :').$e->getCode();
        $trace .= $newLine.$bold('Error Message :').$e->getMessage();
        $trace .= $newLine.$bold('Error File :').$e->getFile();
        $trace .= $newLine.$bold('Error File Line :').$e->getLine();
        $trace .= $newLine.$bold('Error Trace :').$newLine;

        $trace .= ($html) ? preg_replace("/\n/", '<br>', $e->getTraceAsString()) : $e->getTraceAsString();

        return $trace;
    }
657187
public function render(Request $request, Exception $e)
    {
        $e = $this->prepareException($e);

        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } else if ($e instanceof AuthenticationException) {
            return $this->unauthenticated($request, $e);
        } else if ($e instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($e, $request);
        }

        return $this->prepareResponse($request, $e);
    }
1050441
public static function wrapException(RequestInterface $request, \Exception $e)
    {
        return $e instanceof RequestException
            ? $e
            : new RequestException($e->getMessage(), $request, null, $e);
    }
460645
public function handleException($e)
    {
        if (!$e instanceof Exception) {
            $e = new FatalThrowableError($e);
        }

        try {
            $trace = call_user_func(config()->get('exception.log'), $e);
        } catch (Exception $exception) {
            $trace = [
                'original' => explode("\n", $e->getTraceAsString()),
                'handler' => explode("\n", $exception->getTraceAsString()),
            ];
        }

        logger()->log(Logger::ERROR, $e->getMessage(), $trace);

        if (Application::MODE_CLI === $this->mode) {
            throw $e;
        }

        $status = ($e instanceof HttpException) ? $e->getStatusCode() : $e->getCode();

        if (!array_key_exists($status, Response::$statusTexts)) {
            $status = Response::HTTP_INTERNAL_SERVER_ERROR;
        }

        $resposne = json(call_user_func(config()->get('exception.response'), $e), $status);
        if (!$this->isBooted()) {
            $this->handleResponse($resposne);
        }

        return $resposne;
    }
911614
private function wrapException(\Exception $e)
    {
        if ($e instanceof ClientException && $e->getResponse()->getStatusCode() == 404) {
            return NotFoundException::wrap($e);
        }

        return ErrorException::wrap($e);
    }
44547
protected function mask($payload)
    {
        $length = strlen($payload);
        $mask = $this->getMask();

        $unmasked = '';
        for ($i = 0; $i < $length; $i++) {
            $unmasked .= $payload[$i] ^ $mask[$i % 4];
        }

        return $unmasked;
    }
52461
protected function getErrorResponse(Exception $e)
    {
        switch (get_class($e)) {
            case ForbiddenException::class:
                $response = $this->forbidden(
                    new ErrorBag([new Error('Forbidden', $e->getMessage())])
                );
                break;
            default:
                $response = $this->errorResponse(
                    new ErrorBag([new Error('Bad Request', 'Request could not be served.')])
                );
        }

        return $response;
    }
1272250
public function handleException( \Throwable $e ) : bool
    {
        if ( $e instanceof HttpStatusException )
        {
            static $error_messages = [
                // 10X  Information
                // 20X  Normaly Processed
                '200' => 'OK',
    
                // 30X  Moved Content
                '300' => 'Multiple Choices',
                '301' => 'Moved Permanently',
                '302' => 'Moved Temporarily',
                '303' => 'See Other',
                '304' => 'Not Modified',
                '305' => 'Use Proxy',
                '307' => 'Temporary Redirect',
    
                // 40X Failure
                '401' => 'Unauthorized',
                '402' => 'Payment Required',
                '403' => 'Forbidden',
                '404' => 'Not Found',
                '405' => 'Method Not Allowed',
                '406' => 'Not Acceptable',
                '407' => 'Proxy Authentication Required',
                '408' => 'Request Time-out',
                '409' => 'Conflict',
                '410' => 'Gone',
                '411' => 'Length Required',
                '412' => 'Precondition Failed',
                '413' => 'Request Entity Too Large',
                '414' => 'Request-URI Too Large',
                '415' => 'Unsupported Media Type',
                '416' => 'Requested range not satisfiable',
                '417' => 'Expectation Failed',
    
                // 50 Server Error
                '500' => 'Internal Server Error',
                '501' => 'Not Implemented',
                '502' => 'Bad Gateway',
                '503' => 'Service Unavailable',
                '504' => 'Gateway Time-out',
                '505' => 'HTTP Version not supported',
            ];

            $status = $e->getStatusCode();
            $header_msg = $error_messages[$status] ?? '';

            header( "HTTP/1.0 {$status} {$header_msg}", true, $status );
            
            return true;
        }

        return false;
    }