Documentation improvements

This commit is contained in:
Vladimir Razuvaev 2017-08-17 20:35:58 +07:00
parent c65d8d8624
commit c04d037fb1
6 changed files with 122 additions and 82 deletions

View File

@ -1,13 +1,15 @@
# Upgrade
## Upgrade v0.8.x, v0.9.x > v0.10.x ## Upgrade v0.8.x, v0.9.x > v0.10.x
### Breaking: minimum PHP version was changed from 5.4 to 5.5
It allows us to leverage `::class` constant, `generators` and other features of newer PHP versions.
### Breaking: default error formatting ### Breaking: default error formatting
By default exceptions thrown in resolvers will be reported with generic message `"Internal server error"`. By default exceptions thrown in resolvers will be reported with generic message `"Internal server error"`.
Only exceptions implementing interface `GraphQL\Error\ClientAware` and claiming themselves as `safe` will Only exceptions implementing interface `GraphQL\Error\ClientAware` and claiming themselves as `safe` will
be reported with full error message. be reported with full error message.
This is done to avoid information leak in production when unhandled exceptions occur in resolvers This breaking change is done to avoid information leak in production when unhandled
(e.g. database connection errors, file access errors, etc). exceptions were reported to clients (e.g. database connection errors, file access errors, etc).
Also every error reported to client now has new `category` key which is either `graphql` or `internal`. Also every error reported to client now has new `category` key which is either `graphql` or `internal`.
Exceptions implementing `ClientAware` interface may define their own custom categories. Exceptions implementing `ClientAware` interface may define their own custom categories.
@ -27,10 +29,19 @@ GraphQL\Error\FormattedError::setInternalErrorMessage("Unexpected error");
``` ```
**This change only affects default error reporting mechanism. If you set your own error formatter using **This change only affects default error reporting mechanism. If you set your own error formatter using
`ExecutionResult::setErrorFormatter()` you won't be affected by this change.** `$executionResult->setErrorFormatter($myFormatter)` you won't be affected by this change.**
If new default formatting doesn't work for you - just set [your own error If you need to revert to old behavior temporary, use:
formatter](http://webonyx.github.io/graphql-php/error-handling/#custom-error-formatting).
```php
GraphQL::executeAndReturnResult(/**/)
->setErrorFormatter('\GraphQL\Error\Error::formatError')
->toArray();
```
But note that this is deprecated format and will be removed in future versions.
In general, if new default formatting doesn't work for you - just set [your own error
formatter](http://webonyx.github.io/graphql-php/error-handling/#custom-error-handling-and-formatting).
### Breaking: AST now uses `NodeList` vs array for lists of nodes ### Breaking: AST now uses `NodeList` vs array for lists of nodes
It helps us unserialize AST from array lazily. This change affects you only if you use `array_` It helps us unserialize AST from array lazily. This change affects you only if you use `array_`
@ -51,13 +62,39 @@ new GraphQL\Language\AST\DocumentNode([
### Breaking: scalar types now throw different exceptions when parsing and serializing ### Breaking: scalar types now throw different exceptions when parsing and serializing
On invalid user input they throw standard `GraphQL\Error\Error` now, but when they On invalid client input (`parseValue` and `parseLiteral`) they throw standard `GraphQL\Error\Error`
encounter invalid output during serialization they throw `GraphQL\Error\InvariantViolation`. but when they encounter invalid output (in `serialize`) they throw `GraphQL\Error\InvariantViolation`.
Previously they were throwing `GraphQL\Error\UserError`. This exception is no longer used so make sure
to adjust if you were checking for this error in your custom error formatters.
### Breaking: removed previously deprecated ability to define type as callable
See https://github.com/webonyx/graphql-php/issues/35
### Deprecated: `GraphQL\GraphQL::executeAndReturnResult` renamed to `GraphQL\GraphQL::executeQuery`
Old method name is still available, but will trigger deprecation warning in next version.
### Deprecated: `GraphQL\GraphQL::execute`
Use `GraphQL\GraphQL::executeQuery()->toArray()` instead.
Old method still exists, but will trigger deprecation warning in next version.
### Deprecated: `GraphQL\Schema` moved to `GraphQL\Type\Schema`
Old class still exists, but will trigger deprecation warning in next version.
### Deprecated: `GraphQL\Utils` moved to `GraphQL\Utils\Utils` ### Deprecated: `GraphQL\Utils` moved to `GraphQL\Utils\Utils`
Old class still exists, but triggers deprecation warning when referenced. Old class still exists, but triggers deprecation warning when referenced.
### Deprecated: `GraphQL\Type\Definition\Config`
If you were using config validation in previous versions, replace:
```php
GraphQL\Type\Definition\Config::enableValidation();
```
with:
```php
$schema->assertValid();
```
See https://github.com/webonyx/graphql-php/issues/148
## Upgrade v0.7.x > v0.8.x ## Upgrade v0.7.x > v0.8.x
All of those changes apply to those who extends various parts of this library. All of those changes apply to those who extends various parts of this library.
If you only use the library and don't try to extend it - everything should work without breaks. If you only use the library and don't try to extend it - everything should work without breaks.

View File

@ -84,16 +84,16 @@ During development or debugging use `$result->toArray(true)` to add **debugMessa
each formatted error entry. If you also want to add exception trace - pass flags instead: each formatted error entry. If you also want to add exception trace - pass flags instead:
``` ```
use GraphQL\Error\FormattedError; use GraphQL\Error\Debug;
$debug = FormattedError::INCLUDE_DEBUG_MESSAGE | FormattedError::INCLUDE_TRACE; $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::INCLUDE_TRACE;
$result = GraphQL::executeQuery(/*args*/)->toArray($debug); $result = GraphQL::executeQuery(/*args*/)->toArray($debug);
``` ```
This will make each error entry to look like this: This will make each error entry to look like this:
```php ```php
[ [
'message' => 'Internal server error',
'debugMessage' => 'Actual exception message', 'debugMessage' => 'Actual exception message',
'message' => 'Internal server error',
'category' => 'internal', 'category' => 'internal',
'locations' => [ 'locations' => [
['line' => 10, 'column' => 2] ['line' => 10, 'column' => 2]
@ -111,8 +111,8 @@ This will make each error entry to look like this:
If you prefer first resolver exception to be re-thrown, use following flags: If you prefer first resolver exception to be re-thrown, use following flags:
```php ```php
use GraphQL\Error\FormattedError; use GraphQL\Error\Debug;
$debug = FormattedError::INCLUDE_DEBUG_MESSAGE | FormattedError::RETHROW_RESOLVER_EXCEPTIONS; $debug = Debug::INCLUDE_DEBUG_MESSAGE | Debug::RETHROW_INTERNAL_EXCEPTIONS;
// Following will throw if there was an exception in resolver during execution: // Following will throw if there was an exception in resolver during execution:
$result = GraphQL::executeQuery(/*args*/)->toArray($debug); $result = GraphQL::executeQuery(/*args*/)->toArray($debug);
@ -144,7 +144,8 @@ $result = GraphQL::executeQuery(/* $args */)
->toArray(); ->toArray();
``` ```
You may also re-throw exceptions in result handler for debugging, etc. Note that when you pass [debug flags](#debugging-tools) to `$result->toArray` your custom formatter will still be
decorated with same debugging information mentioned above.
# Schema Errors # Schema Errors
So far we only covered errors which occur during query execution process. But schema definition can So far we only covered errors which occur during query execution process. But schema definition can

View File

@ -1,4 +1,4 @@
# Overview # Using Facade Method
Query execution is a complex process involving multiple steps, including query **parsing**, Query execution is a complex process involving multiple steps, including query **parsing**,
**validating** and finally **executing** against your [schema](type-system/schema/). **validating** and finally **executing** against your [schema](type-system/schema/).
@ -33,7 +33,7 @@ Returned array contains **data** and **errors** keys, as described by
This array is suitable for further serialization (e.g. using `json_encode`). This array is suitable for further serialization (e.g. using `json_encode`).
See also section on [error handling and formatting](error-handling/). See also section on [error handling and formatting](error-handling/).
Description of method arguments: Description of `executeQuery` method arguments:
Argument | Type | Notes Argument | Type | Notes
------------ | -------- | ----- ------------ | -------- | -----
@ -47,59 +47,7 @@ fieldResolver | `callable` | A resolver function to use when one is not provided
validationRules | `array` | A set of rules for query validation step. Default value is all available rules. Empty array would allow to skip query validation (may be convenient for persisted queries which are validated before persisting and assumed valid during execution) validationRules | `array` | A set of rules for query validation step. Default value is all available rules. Empty array would allow to skip query validation (may be convenient for persisted queries which are validated before persisting and assumed valid during execution)
promiseAdapter | `GraphQL\Executir\Promise\PromiseAdapter` | Adapter for async-enabled PHP platforms like ReactPHP (read about [async platforms integration](data-fetching/#async-php)) promiseAdapter | `GraphQL\Executir\Promise\PromiseAdapter` | Adapter for async-enabled PHP platforms like ReactPHP (read about [async platforms integration](data-fetching/#async-php))
# Execution Result # Using Server
```php If you are building HTTP GraphQL API, you may prefer GraphQL [Standard Server](/server/) which supports
namespace GraphQL\Executor; more features out of the box, including parsing HTTP requests, batching queries (apollo style)
and producing response.
class ExecutionResult
{
/**
* @var array
*/
public $data;
/**
* @var GraphQL\Error\Error[]
*/
public $errors;
/**
*
*/
public setErrorsHandler(callable $errorsHandler);
public setErrorFormatter(callable $errorsHandler);
}
```
# Parsing
Following reading describes implementation details of query execution process. It may clarify some
internals of GraphQL but is not required to use it. Feel free to skip to next section
on [Error Handling](error-handling/) for essentials.
TODOC
# Validating
TODOC
# Executing
TODOC
# Errors explained
There are 3 types of errors in GraphQL:
- **Syntax**: query has invalid syntax and could not be parsed;
- **Validation**: query is incompatible with type system (e.g. unknown field is requested);
- **Execution**: occurs when some field resolver throws (or returns unexpected value).
Obviously when **Syntax** or **Validation** error is detected - process is interrupted and query is not
executed.
GraphQL is forgiving to **Execution** errors which occur in resolvers of nullable fields.
If such field throws or returns unexpected value the value of the field in response will be simply
replaced with `null` and error entry will be registered.
If exception is thrown in non-null field - error bubbles up to first nullable field. This nullable field is
replaced with `null` and error entry is added to response. If all fields up to the root are non-null -
**data** entry will be removed from response and only **errors** key will be presented.

31
docs/how-it-works.md Normal file
View File

@ -0,0 +1,31 @@
# Overview
Following reading describes implementation details of query execution process. It may clarify some
internals of GraphQL runtime but is not required to use it.
# Parsing
TODOC
# Validating
TODOC
# Executing
TODOC
# Errors explained
There are 3 types of errors in GraphQL:
- **Syntax**: query has invalid syntax and could not be parsed;
- **Validation**: query is incompatible with type system (e.g. unknown field is requested);
- **Execution**: occurs when some field resolver throws (or returns unexpected value).
Obviously when **Syntax** or **Validation** error is detected - process is interrupted and query is not
executed.
GraphQL is forgiving to **Execution** errors which occur in resolvers of nullable fields.
If such field throws or returns unexpected value the value of the field in response will be simply
replaced with `null` and error entry will be registered.
If exception is thrown in non-null field - error bubbles up to first nullable field. This nullable field is
replaced with `null` and error entry is added to response. If all fields up to the root are non-null -
**data** entry will be removed from response and only **errors** key will be presented.

View File

@ -863,21 +863,28 @@ interface ClientAware
} }
``` ```
# GraphQL\Error\Debug
```php
namespace GraphQL\Error;
class Debug
{
const INCLUDE_DEBUG_MESSAGE = 1;
const INCLUDE_TRACE = 2;
const RETHROW_INTERNAL_EXCEPTIONS = 4;
}
```
# GraphQL\Error\FormattedError # GraphQL\Error\FormattedError
```php ```php
namespace GraphQL\Error; namespace GraphQL\Error;
class FormattedError class FormattedError
{ {
const INCLUDE_DEBUG_MESSAGE = 1;
const INCLUDE_TRACE = 2;
const RETHROW_RESOLVER_EXCEPTIONS = 4;
public static function setInternalErrorMessage($msg); public static function setInternalErrorMessage($msg);
/** /**
* Standard GraphQL error formatter. Converts any exception to GraphQL error * Standard GraphQL error formatter. Converts any exception to array conforming to GraphQL spec
* conforming to GraphQL spec
* *
* @param \Throwable $e * @param \Throwable $e
* @param bool|int $debug * @param bool|int $debug
@ -886,5 +893,20 @@ class FormattedError
* @return array * @return array
*/ */
public static function createFromException($e, $debug = false, $internalErrorMessage = null); public static function createFromException($e, $debug = false, $internalErrorMessage = null);
/**
* Adds "debugMessage", "trace", "file", "line" entries to $formattedError.
*
* @return array
*/
public static function addDebugEntries(array $formattedError, $e, $debug);
/**
* Prepares final error formatter taking in account $debug flags.
* If initial formatter is not set, FormattedError::createFromException is used
*
* @return callable|\Closure
*/
public static function prepareFormatter(callable $formatter = null, $debug);
} }
``` ```

View File

@ -13,14 +13,15 @@ pages:
- Input Types: type-system/input-types.md - Input Types: type-system/input-types.md
- Directives: type-system/directives.md - Directives: type-system/directives.md
- Schema: type-system/schema.md - Schema: type-system/schema.md
# - Using Type Language: type-system/type-language.md - Using Type Language: type-system/type-language.md
- Executing Queries: executing-queries.md - Executing Queries: executing-queries.md
- Fetching Data: data-fetching.md - Fetching Data: data-fetching.md
- Handling Errors: error-handling.md - Handling Errors: error-handling.md
# - Mutations: mutations.md
# - Security: security.md # - Security: security.md
# - Performance tips: performance.md # - Performance tips: performance.md
# - Standard Server: server.md # - Standard Server: server.md
# - Best Practices: best-practices.md - How it works: how-it-works.md
- Complementary Tools: complementary-tools.md
- Class Reference: reference.md - Class Reference: reference.md
- Complementary Tools: complementary-tools.md
theme: readthedocs theme: readthedocs