diff --git a/CHANGELOG.md b/CHANGELOG.md index c273f5a0e23..110b565aaba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ * Pass `ctx` instead of `ctx.request` to options function in Koa integration ([@HriBB](https://github.com/HriBB)) in [PR #154](https://github.com/apollostack/apollo-server/pull/154) * Manage TypeScript declaration files using npm. ([@od1k](https:/github.com/od1k) in [#162](https://github.com/apollostack/apollo-server/pull/162)) * Fix connect example in readme. ([@conrad-vanl](https://github.com/conrad-vanl) in [#165](https://github.com/apollostack/apollo-server/pull/165)) +* Add try/catch to formatError. ([@nicolaslopezj](https://github.com/nicolaslopezj) in [#174](https://github.com/apollostack/apollo-server/pull/174)) ### v0.3.2 * Added missing exports for hapi integration ([@nnance](https://github.com/nnance)) in [PR #152](https://github.com/apollostack/apollo-server/pull/152) diff --git a/src/core/runQuery.ts b/src/core/runQuery.ts index ef5314d24c9..edad9c031c4 100644 --- a/src/core/runQuery.ts +++ b/src/core/runQuery.ts @@ -69,11 +69,19 @@ function doRunQuery(options: QueryOptions): Promise { logFunction({action: LogAction.request, step: LogStep.start}); function format(errors: Array): Array { - // TODO: fix types! shouldn't have to cast. - // the blocker is that the typings aren't right atm: - // GraphQLResult returns Array, but the formatError function - // returns Array - return errors.map(options.formatError || formatError as any) as Array; + return errors.map((error) => { + if (options.formatError) { + try { + return options.formatError(error); + } catch (err) { + console.error('Error in formatError function:', err); + const newError = new Error('Internal server error'); + return formatError(newError); + } + } else { + return formatError(error); + } + }) as Array; } function printStackTrace(error: Error) { diff --git a/src/integrations/integrations.test.ts b/src/integrations/integrations.test.ts index 328a43c7a5d..8ed6a0b7e93 100644 --- a/src/integrations/integrations.test.ts +++ b/src/integrations/integrations.test.ts @@ -436,6 +436,23 @@ export default (createApp: CreateAppFunc, destroyApp?: DestroyAppFunc) => { }); }); + it('sends internal server error when formatError fails', () => { + app = createApp({apolloOptions: { + schema: Schema, + formatError: (err) => { + throw new Error('I should be catched'); + }, + }}); + const req = request(app) + .post('/graphql') + .send({ + query: 'query test{ testError }', + }); + return req.then((res) => { + return expect(res.res.body.errors[0].message).to.equal('Internal server error'); + }); + }); + it('sends stack trace to error if debug mode is set', () => { const expected = /at resolveOrError/; const stackTrace = [];