Skip to content
This repository was archived by the owner on Mar 20, 2023. It is now read-only.

support for adding optional error handling function before returning … #118

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ The `graphqlHTTP` function accepts the following options:
* **`validationRules`**: Optional additional validation rules queries must
satisfy in addition to those defined by the GraphQL spec.

* **`handleErrors`**: An optional function which will be used to handle any errors
encountered by fulfilling a GraphQL operation. If no function is provided, Errors
will default to normal behavior and return in `errors` array.

## HTTP Usage

Expand Down
10 changes: 10 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ export type OptionsData = {
* A boolean to optionally enable GraphiQL mode.
*/
graphiql?: ?boolean,

/**
* An optional function which will be used to handle any errors encountered
* by fulfilling a GraphQL operation. If no function is provided, Errors will
* be handled by default.
*/
handleErrors?: ?Function,
};

type Middleware = (request: Request, response: Response) => Promise<void>;
Expand Down Expand Up @@ -101,6 +108,7 @@ export default function graphqlHTTP(options: Options): Middleware {
let variables;
let operationName;
let validationRules;
let handleErrorsFn;

// Promises are used as a mechanism for capturing any thrown errors during
// the asynchronous process below.
Expand Down Expand Up @@ -135,6 +143,7 @@ export default function graphqlHTTP(options: Options): Middleware {
pretty = optionsData.pretty;
graphiql = optionsData.graphiql;
formatErrorFn = optionsData.formatError;
handleErrorsFn = optionsData.handleErrors;

validationRules = specifiedRules;
if (optionsData.validationRules) {
Expand Down Expand Up @@ -233,6 +242,7 @@ export default function graphqlHTTP(options: Options): Middleware {
// Format any encountered errors.
if (result && result.errors) {
result.errors = result.errors.map(formatErrorFn || formatError);
if (handleErrorsFn) { handleErrorsFn(result, response); }
}
// If allowed to show GraphiQL, present it instead of JSON.
if (showGraphiQL) {
Expand Down