FormattedError.php 11.5 KB
Newer Older
Ketan's avatar
Ketan committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
<?php
namespace GraphQL\Error;

use GraphQL\Language\AST\Node;
use GraphQL\Language\Source;
use GraphQL\Language\SourceLocation;
use GraphQL\Type\Definition\Type;
use GraphQL\Type\Definition\WrappingType;
use GraphQL\Utils\Utils;

/**
 * This class is used for [default error formatting](error-handling.md).
 * It converts PHP exceptions to [spec-compliant errors](https://facebook.github.io/graphql/#sec-Errors)
 * and provides tools for error debugging.
 */
class FormattedError
{
    private static $internalErrorMessage = 'Internal server error';

    /**
     * Set default error message for internal errors formatted using createFormattedError().
     * This value can be overridden by passing 3rd argument to `createFormattedError()`.
     *
     * @api
     * @param string $msg
     */
    public static function setInternalErrorMessage($msg)
    {
        self::$internalErrorMessage = $msg;
    }

    /**
     * Prints a GraphQLError to a string, representing useful location information
     * about the error's position in the source.
     *
     * @param Error $error
     * @return string
     */
    public static function printError(Error $error)
    {
        $printedLocations = [];
        if ($error->nodes) {
            /** @var Node $node */
            foreach($error->nodes as $node) {
                if ($node->loc) {
                    $printedLocations[] = self::highlightSourceAtLocation(
                        $node->loc->source,
                        $node->loc->source->getLocation($node->loc->start)
                    );
                }
            }
        } else if ($error->getSource() && $error->getLocations()) {
            $source = $error->getSource();
            foreach($error->getLocations() as $location) {
                $printedLocations[] = self::highlightSourceAtLocation($source, $location);
            }
        }

        return !$printedLocations
            ? $error->getMessage()
            : join("\n\n", array_merge([$error->getMessage()], $printedLocations)) . "\n";
    }

    /**
     * Render a helpful description of the location of the error in the GraphQL
     * Source document.
     *
     * @param Source $source
     * @param SourceLocation $location
     * @return string
     */
    private static function highlightSourceAtLocation(Source $source, SourceLocation $location)
    {
        $line = $location->line;
        $lineOffset = $source->locationOffset->line - 1;
        $columnOffset = self::getColumnOffset($source, $location);
        $contextLine = $line + $lineOffset;
        $contextColumn = $location->column + $columnOffset;
        $prevLineNum = (string) ($contextLine - 1);
        $lineNum = (string) $contextLine;
        $nextLineNum = (string) ($contextLine + 1);
        $padLen = strlen($nextLineNum);
        $lines = preg_split('/\r\n|[\n\r]/', $source->body);

        $lines[0] = self::whitespace($source->locationOffset->column - 1) . $lines[0];

        $outputLines = [
            "{$source->name} ($contextLine:$contextColumn)",
            $line >= 2 ? (self::lpad($padLen, $prevLineNum) . ': ' . $lines[$line - 2]) : null,
            self::lpad($padLen, $lineNum) . ': ' . $lines[$line - 1],
            self::whitespace(2 + $padLen + $contextColumn - 1) . '^',
            $line < count($lines)? self::lpad($padLen, $nextLineNum) . ': ' . $lines[$line] : null
        ];

        return join("\n", array_filter($outputLines));
    }

    /**
     * @param Source $source
     * @param SourceLocation $location
     * @return int
     */
    private static function getColumnOffset(Source $source, SourceLocation $location)
    {
        return $location->line === 1 ? $source->locationOffset->column - 1 : 0;
    }

    /**
     * @param int $len
     * @return string
     */
    private static function whitespace($len) {
        return str_repeat(' ', $len);
    }

    /**
     * @param int $len
     * @return string
     */
    private static function lpad($len, $str) {
        return self::whitespace($len - mb_strlen($str)) . $str;
    }

    /**
     * Standard GraphQL error formatter. Converts any exception to array
     * conforming to GraphQL spec.
     *
     * This method only exposes exception message when exception implements ClientAware interface
     * (or when debug flags are passed).
     *
     * For a list of available debug flags see GraphQL\Error\Debug constants.
     *
     * @api
     * @param \Throwable $e
     * @param bool|int $debug
     * @param string $internalErrorMessage
     * @return array
     * @throws \Throwable
     */
    public static function createFromException($e, $debug = false, $internalErrorMessage = null)
    {
        Utils::invariant(
            $e instanceof \Exception || $e instanceof \Throwable,
            "Expected exception, got %s",
            Utils::getVariableType($e)
        );

        $internalErrorMessage = $internalErrorMessage ?: self::$internalErrorMessage;

        if ($e instanceof ClientAware) {
            $formattedError = [
                'message' => $e->isClientSafe() ? $e->getMessage() : $internalErrorMessage,
                'category' => $e->getCategory()
            ];
        } else {
            $formattedError = [
                'message' => $internalErrorMessage,
                'category' => Error::CATEGORY_INTERNAL
            ];
        }

        if ($e instanceof Error) {
            if ($e->getExtensions()) {
                $formattedError = array_merge($e->getExtensions(), $formattedError);
            }

            $locations = Utils::map($e->getLocations(), function(SourceLocation $loc) {
                return $loc->toSerializableArray();
            });

            if (!empty($locations)) {
                $formattedError['locations'] = $locations;
            }
            if (!empty($e->path)) {
                $formattedError['path'] = $e->path;
            }
        }

        if ($debug) {
            $formattedError = self::addDebugEntries($formattedError, $e, $debug);
        }

        return $formattedError;
    }

    /**
     * Decorates spec-compliant $formattedError with debug entries according to $debug flags
     * (see GraphQL\Error\Debug for available flags)
     *
     * @param array $formattedError
     * @param \Throwable $e
     * @param bool $debug
     * @return array
     * @throws \Throwable
     */
    public static function addDebugEntries(array $formattedError, $e, $debug)
    {
        if (!$debug) {
            return $formattedError;
        }

        Utils::invariant(
            $e instanceof \Exception || $e instanceof \Throwable,
            "Expected exception, got %s",
            Utils::getVariableType($e)
        );

        $debug = (int) $debug;

        if ($debug & Debug::RETHROW_INTERNAL_EXCEPTIONS) {
            if (!$e instanceof Error) {
                throw $e;
            } else if ($e->getPrevious()) {
                throw $e->getPrevious();
            }
        }

        $isInternal = !$e instanceof ClientAware || !$e->isClientSafe();

        if (($debug & Debug::INCLUDE_DEBUG_MESSAGE) && $isInternal) {
            // Displaying debugMessage as a first entry:
            $formattedError = ['debugMessage' => $e->getMessage()] + $formattedError;
        }

        if ($debug & Debug::INCLUDE_TRACE) {
            if ($e instanceof \ErrorException || $e instanceof \Error) {
                $formattedError += [
                    'file' => $e->getFile(),
                    'line' => $e->getLine(),
                ];
            }

            $isTrivial = $e instanceof Error && !$e->getPrevious();

            if (!$isTrivial) {
                $debugging = $e->getPrevious() ?: $e;
                $formattedError['trace'] = static::toSafeTrace($debugging);
            }
        }
        return $formattedError;
    }

    /**
     * Prepares final error formatter taking in account $debug flags.
     * If initial formatter is not set, FormattedError::createFromException is used
     *
     * @param callable|null $formatter
     * @param $debug
     * @return callable|\Closure
     */
    public static function prepareFormatter(callable $formatter = null, $debug)
    {
        $formatter = $formatter ?: function($e) {
            return FormattedError::createFromException($e);
        };
        if ($debug) {
            $formatter = function($e) use ($formatter, $debug) {
                return FormattedError::addDebugEntries($formatter($e), $e, $debug);
            };
        }
        return $formatter;
    }

    /**
     * Returns error trace as serializable array
     *
     * @api
     * @param \Throwable $error
     * @return array
     */
    public static function toSafeTrace($error)
    {
        $trace = $error->getTrace();

        // Remove invariant entries as they don't provide much value:
        if (
            isset($trace[0]['function']) && isset($trace[0]['class']) &&
            ('GraphQL\Utils\Utils::invariant' === $trace[0]['class'].'::'.$trace[0]['function'])) {
            array_shift($trace);
        }

        // Remove root call as it's likely error handler trace:
        else if (!isset($trace[0]['file'])) {
            array_shift($trace);
        }

        return array_map(function($err) {
            $safeErr = array_intersect_key($err, ['file' => true, 'line' => true]);

            if (isset($err['function'])) {
                $func = $err['function'];
                $args = !empty($err['args']) ? array_map([__CLASS__, 'printVar'], $err['args']) : [];
                $funcStr = $func . '(' . implode(", ", $args) . ')';

                if (isset($err['class'])) {
                    $safeErr['call'] = $err['class'] . '::' . $funcStr;
                } else {
                    $safeErr['function'] = $funcStr;
                }
            }

            return $safeErr;
        }, $trace);
    }

    /**
     * @param $var
     * @return string
     */
    public static function printVar($var)
    {
        if ($var instanceof Type) {
            // FIXME: Replace with schema printer call
            if ($var instanceof WrappingType) {
                $var = $var->getWrappedType(true);
            }
            return 'GraphQLType: ' . $var->name;
        }

        if (is_object($var)) {
            return 'instance of ' . get_class($var) . ($var instanceof \Countable ? '(' . count($var) . ')' : '');
        }
        if (is_array($var)) {
            return 'array(' . count($var) . ')';
        }
        if ('' === $var) {
            return '(empty string)';
        }
        if (is_string($var)) {
            return "'" . addcslashes($var, "'") . "'";
        }
        if (is_bool($var)) {
            return $var ? 'true' : 'false';
        }
        if (is_scalar($var)) {
            return $var;
        }
        if (null === $var) {
            return 'null';
        }
        return gettype($var);
    }

    /**
     * @deprecated as of v0.8.0
     * @param $error
     * @param SourceLocation[] $locations
     * @return array
     */
    public static function create($error, array $locations = [])
    {
        $formatted = [
            'message' => $error
        ];

        if (!empty($locations)) {
            $formatted['locations'] = array_map(function($loc) { return $loc->toArray();}, $locations);
        }

        return $formatted;
    }

    /**
     * @param \ErrorException $e
     * @deprecated as of v0.10.0, use general purpose method createFromException() instead
     * @return array
     */
    public static function createFromPHPError(\ErrorException $e)
    {
        return [
            'message' => $e->getMessage(),
            'severity' => $e->getSeverity(),
            'trace' => self::toSafeTrace($e)
        ];
    }
}