From b4626534ba64917f1af1dd8b38318ded68e72f03 Mon Sep 17 00:00:00 2001 From: Ivan Goncharov Date: Mon, 9 Nov 2020 19:43:58 +0200 Subject: [PATCH] Use HTTP code of underlying errors (#715) Fixes #702 --- src/__tests__/http-test.ts | 2 +- src/parseBody.ts | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/__tests__/http-test.ts b/src/__tests__/http-test.ts index ffca7714..54fbcd0d 100644 --- a/src/__tests__/http-test.ts +++ b/src/__tests__/http-test.ts @@ -1462,7 +1462,7 @@ function runTests(server: Server) { .set('Content-Type', 'application/json') .send(`{ "query": "{ ${new Array(102400).fill('test').join('')} }" }`); - expect(response.status).to.equal(400); + expect(response.status).to.equal(413); expect(JSON.parse(response.text)).to.deep.equal({ errors: [{ message: 'Invalid body: request entity too large.' }], }); diff --git a/src/parseBody.ts b/src/parseBody.ts index 3cac4c3d..0fd3e4f4 100644 --- a/src/parseBody.ts +++ b/src/parseBody.ts @@ -100,10 +100,18 @@ async function readBody( // Read body from stream. try { return await getBody(stream, { encoding: charset, length, limit }); - } catch (err) { - throw err.type === 'encoding.unsupported' - ? httpError(415, `Unsupported charset "${charset.toUpperCase()}".`) - : httpError(400, `Invalid body: ${String(err.message)}.`); + } catch (rawError: unknown) { + const error = httpError( + 400, + /* istanbul ignore next: Thrown by underlying library. */ + rawError instanceof Error ? rawError : String(rawError), + ); + + error.message = + error.type === 'encoding.unsupported' + ? `Unsupported charset "${charset.toUpperCase()}".` + : `Invalid body: ${error.message}.`; + throw error; } }