Log API error.

@author Vova Feldman (@svovaf)
@since  1.2.1.5

@param mixed $api_result
@param bool  $wrapper
320617
function api_error( $api_result, $wrapper = false ) {
			$message = '';
			if ( is_object( $api_result ) &&
			     ! empty( $api_result->error ) &&
			     ! empty( $api_result->error->message )
			) {
				$message = $api_result->error->message;
			} else if ( is_object( $api_result ) ) {
				$message = var_export( $api_result, true );
			} else if ( is_string( $api_result ) ) {
				$message = $api_result;
			} else if ( empty( $api_result ) ) {
				$message = 'Empty API result.';
			}

			$message = 'API Error: ' . $message;

			$this->_log( $message, 'error', $wrapper );
		}
386661
public function setOutput($output, ? string $wrapper = null)
    {
        if ($wrapper) {
            $this->setOutputWrapper($wrapper);
        }

        return tap($this, function ($instance) use ($output) {
            $instance->output = $output;
        });
    }
1100147
protected function handleRequestError($result)
    {
        /**
         * Curl error
         */
        if ($result === false) {
            throw new Exception\TransferError($this->request->getErrorString(), $this->request->getErrorCode());
        }

        switch ($this->request->getResponseHTTPCode()) {
            case 401:
                $this->error($result, ['CODE'=>401]);
                throw new Exception\AuthenticationFailure($result, 401);
                break;
            case 403:
                $this->error($result, ['CODE'=>403]);
                throw new Exception\AccessDenied($result, 403);
                break;
            case 404:
                //sometimes it's a json string, sometimes it's not... so there's that.
                if (stripos($result, '{') === 0) {
                    $error = json_decode($result);
                    $errorMessage = $error->Message;
                }
                else {
                    $errorMessage = $result;
                }
                $this->error($errorMessage, ['CODE'=>404]);
                throw new Exception\NotFound($errorMessage, 404);
                break;
        }
    }
390193
public function errors(int $statusCode, string $message, $errors = null): void
    {
        $this->setStatusCode($statusCode);
        $this->setMessage($message);
        $this->setErrors($errors);

        throw new ApiException($this);
    }
72384
function logError( $message, array $more_info = [] ) {

		/** $var \WP_User $current_user */
		global $current_user;

		$subject = get_class( $this );

		$info = [
			'time' => strftime( '%c' ),
			'user' => ( isset( $current_user ) ? $current_user->user_login : '__UNKNOWN__' ),
			'site_url' => site_url(),
			'blog_id' => get_current_blog_id(),
			'theme' => '' . wp_get_theme(), // Stringify by appending to empty string
		];

		$message = print_r( array_merge( $info, $more_info ), true ) . $message; // @codingStandardsIgnoreLine
		$exportoptions = get_option( 'pressbooks_export_options' );
		if ( $current_user->user_email && isset( $exportoptions['email_validation_logs'] ) && 1 === absint( $exportoptions['email_validation_logs'] ) ) {
			$this->errorsEmail[] = $current_user->user_email;
		}

		if ( defined( 'WP_TESTS_MULTISITE' ) ) {
			// Unit tests
			if ( empty( $more_info['warning'] ) ) {
				error_log( "\n{$subject}\n{$message}\n" ); // @codingStandardsIgnoreLine
			}
		} else {
			\Pressbooks\Utility\email_error_log( $this->errorsEmail, $subject, $message );
		}
	}
871995
function logError( $message, array $more_info = [] ) {

		$more_info['path'] = $this->outputPath;

		parent::logError( $message, $more_info );
	}
1165513
public function logResult($resultData = null, $url = null)
    {
        $logResult = false;
        if (isset($resultData['success']) && ($resultData['success'] == 'false')) {
            if (isset($resultData['message'])) {
                $this->addStatusMessage($resultData['message'], 'warning');
            }
            $this->addStatusMessage('Error '.$this->lastResponseCode.': '.urldecode($url),
                'warning');
            unset($url);
        }
        if (is_null($resultData)) {
            $resultData = $this->lastResult;
        }
        if (isset($url)) {
            $this->logger->addStatusMessage($this->lastResponseCode.':'.urldecode($url));
        }

        if (isset($resultData['results'])) {
            if ($resultData['success'] == 'false') {
                $status = 'error';
            } else {
                $status = 'success';
            }
            foreach ($resultData['results'] as $result) {
                if (isset($result['request-id'])) {
                    $rid = $result['request-id'];
                } else {
                    $rid = '';
                }
                if (isset($result['errors'])) {
                    foreach ($result['errors'] as $error) {
                        $message = $error['message'];
                        if (isset($error['for'])) {
                            $message .= ' for: '.$error['for'];
                        }
                        if (isset($error['value'])) {
                            $message .= ' value:'.$error['value'];
                        }
                        if (isset($error['code'])) {
                            $message .= ' code:'.$error['code'];
                        }
                        $this->addStatusMessage($rid.': '.$message, $status);
                    }
                }
            }
        }
        return $logResult;
    }
696256
protected function _fail( $message, $result = false)
    {
        // @todo Investigate the right function
        if ( $result !== false )
        {
            $message .= "\n" . pg_result_error( $result, PGSQL_DIAG_SQLSTATE ) . ": " . pg_result_error( $result, PGSQL_DIAG_MESSAGE_PRIMARY );
        }
        else
        {
            $errorInfo = $this->db->errorInfo();
            $message .= "\n$errorInfo[2]";
        }
        throw new Exception( $message );
    }
420971
public static function post_retry($apiUrl, $data)
    {
        $urlarr = parse_url($apiUrl);
        parse_str($urlarr['query'], $parr);

        usleep(500000);

        $parr['access_token'] = self::getAccessToken();

        $apiUrl = $urlarr['scheme'] . '://' . $urlarr['host'] . $urlarr['path'];
        $apiUrl .= '?' . http_build_query($parr);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
        curl_setopt($ch, CURLOPT_URL, $apiUrl);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        $res      = trim(curl_exec($ch));
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        $header = '';
        $body   = $res;
        if ($httpcode == 200) {
            list($header, $body) = explode("\r\n\r\n", $res, 2);
            //list($header, $body) = explode("keep-alive", $res, 2);
            $header = self::http_parse_headers($header);
        }

        $result           = [];
        $result['info']   = $body;
        $result['header'] = $header;
        $result['status'] = $httpcode;

        $rest_retry = self::packData($result);
        if ($rest_retry === 'retry') {
            return false;
        }

        return $rest_retry;
    }
825291
public static function registerWrapper($wrapper)
    {
        $wrapper = (string) $wrapper;
        if (!in_array($wrapper, static::$wrapperRegistry, true)) {
            static::$wrapperRegistry[] = $wrapper;
        }
    }
985794
private function result()
    {
        // TODO: Call $this->onError(); hook

        // FIXME: Should be executed when exception is caught
        if (false) {
            // If not valid, return an error message to the tool consumer if a return URL is provided
            if (!empty($this->returnUrl)) {
                $error_url = $this->returnUrl;
                if (strpos($error_url, '?') === false) {
                    $error_url .= '?';
                } else {
                    $error_url .= '&';
                }
                if ($this->debugMode && !is_null($this->reason)) {
                    $error_url .= 'lti_errormsg=' . urlencode("Debug error: $this->reason");
                } else {
                    $error_url .= 'lti_errormsg=' . urlencode($this->message);
                    if (!is_null($this->reason)) {
                        $error_url .= '&lti_errorlog=' . urlencode("Debug error: $this->reason");
                    }
                }
                if (!is_null($this->consumer) && isset($_POST['lti_message_type']) && ($_POST['lti_message_type'] === 'ContentItemSelectionRequest')) {
                    $form_params = [];
                    if (isset($_POST['data'])) {
                        $form_params['data'] = $_POST['data'];
                    }
                    $version = (isset($_POST['lti_version'])) ? $_POST['lti_version'] : ToolProvider::LTI_VERSION1;
                    $form_params = $this->consumer->signParameters($error_url, 'ContentItemSelection', $version, $form_params);
                    $page = ToolProvider::sendForm($error_url, $form_params);
                    echo $page;
                } else {
                    header("Location: {$error_url}");
                }
                exit;
            } else {
                if (!is_null($this->errorOutput)) {
                    echo $this->errorOutput;
                } else if ($this->debugMode && !empty($this->reason)) {
                    echo "Debug error: {$this->reason}";
                } else {
                    echo "Error: {$this->message}";
                }
            }
        } else if (!is_null($this->redirectUrl)) {
            header("Location: {$this->redirectUrl}");
            exit;
        } else if (!is_null($this->output)) {
            echo $this->output;
        }
    }
1310418
protected function handleErrorResponse(string $body, array $headers, int $status, string $url): void
    {
        switch ($status) {
            case 400:
            case 405:
                $returnArray = json_decode($body, true);
                throw new ApiSyntaxException($returnArray['message']);
            case 401:
            case 403:
                $returnArray = json_decode($body, true);
                $message = $returnArray['message'] ?? 'Invalid credentials';

                if (isset($returnArray['hint'])) {
                    $message .= ': ' . $returnArray['hint'];
                }

                throw new ApiAuthenticationException($message);
            case 410:
            case 404:
                throw new ApiNotFoundException($url);
                break;
            default:
                $returnArray = json_decode($body, true);
                throw new ApiGeneralException($this->generalExceptionMessage($returnArray ?? [], $headers));
        }
    }
208772
private function log_http_error( $data, $context, $class, array $args = [], $url = '' ) {

		$msg      = 'WP HTTP API Error';
		$response = is_array( $data ) && isset( $data[ 'response' ] ) && is_array( $data[ 'response' ] )
			? shortcode_atts( [ 'message' => '', 'code' => '', 'body' => '' ], $data[ 'response' ] )
			: [ 'message' => '', 'code' => '', 'body' => '' ];

		if ( is_wp_error( $data ) ) {
			$msg .= ': ' . $data->get_error_message();
		} elseif ( is_string( $response[ 'message' ] ) && $response[ 'message' ] ) {
			$msg .= ': ' . $response[ 'message' ];
		}

		$log_context = [
			'transport'  => $class,
			'context'    => $context,
			'query_args' => $args,
			'url'        => $url,
		];

		if ( $response[ 'body' ] && is_string( $response[ 'body' ] ) ) {
			$log_context[ 'response_body' ] = strlen( $response[ 'body' ] ) <= 300
				? $response[ 'body' ]
				: substr( $response[ 'body' ], 0, 300 ) . '...';
		}

		if ( array_key_exists( 'code', $response ) && is_scalar( $response[ 'code' ] ) ) {
			$msg .= " - Response code: {$response[ 'code' ]}";
			( is_array( $data ) && ! empty( $data[ 'headers' ] ) ) and $log_context[ 'headers' ] = $data[ 'headers' ];
		}

		return new Error( rtrim( $msg, '.' ) . '.', Channels::HTTP, $log_context );
	}
230256
function logError($errorMessage, \Exception $exception)
    {
        if ($this->logger instanceof LoggerInterface) {
            $this->logger->error($errorMessage . "\n" . $exception->getTraceAsString());
        }
    }
693186
public static function log($result, $content, $use_rt = true)
    {
        try {
            if ($result['ok'] === false) {
                self::$self = new self();
                $e = new \Exception();
                $error = PHP_EOL;
                $error .= '==========[Response]==========';
                $error .= "\n";
                foreach ($result as $key => $value) {
                    if ($value == false) {
                        $error .= $key.":\t\t\tFalse\n";
                    } else {
                        $error .= $key.":\t\t".$value."\n";
                    }
                }
                $array = '=========[Sent Data]==========';
                $array .= "\n";
                if ($use_rt == true) {
                    foreach ($content as $item) {
                        $array .= self::$self->rt($item).PHP_EOL.PHP_EOL;
                    }
                } else {
                    foreach ($content as $key => $value) {
                        $array .= $key.":\t\t".$value."\n";
                    }
                }
                $backtrace = '============[Trace]===========';
                $backtrace .= "\n";
                $backtrace .= $e->getTraceAsString();
                self::$self->_log_to_file($error.$array.$backtrace);
            }
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
1140618
def api_call(fn):
    

    @wraps(fn)
    def wrapper(*args, **kwargs):
        try:
            result = fn(*args, **kwargs)
        except (DagobahError, DAGValidationError) as e:
            if request and request.endpoint == fn.__name__:
                return jsonify(error_type=type(e).__name__, message=e.message), 400
            raise e
        except Exception as e:
            logging.exception(e)
            raise e

        if request and request.endpoint == fn.__name__:
            status_code = None
            try:
                if result and '_status' in result:
                    status_code = result['_status']
                    del result['_status']
            except TypeError:
                pass

            if isinstance(result, dict):
                if 'result' in result:
                    return jsonify(status=status_code if status_code else 200,
                                   **result)
                else:
                    return jsonify(status=status_code if status_code else 200,
                                   result=result)
            else:
                return jsonify(status=status_code if status_code else 200,
                               result=result)

        else:
            return result

    return wrapper
984930
public function isValid($api_key)
    {
        if (!$api_key) {
            return false;
        }

        return ($this->event_hash == $this->calculateHash($api_key))
            ? true : false;
    }