From e067c9ca67cc2593390afc37ae1e797292811dc9 Mon Sep 17 00:00:00 2001 From: Lucas Werkmeister Date: Tue, 9 Apr 2024 20:45:30 +0200 Subject: [PATCH] Support non-200 response status codes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit These are used by a few API modules, notably some WikiLambda APIs (or Wikifunctions APIs, as they’re apparently starting to be called now). I hope that checking for the MediaWiki-API-Error response header is enough to distinguish between such responses and genuine internal errors that we shouldn’t even try to decode. Only unit-tested, because this feature is so rare that none of the APIs using it seem suitable for an integration test against a real MediaWiki. Fixes #30. --- CHANGES.md | 5 +++++ core.js | 2 +- test/unit/core.test.js | 12 +++++++++++- 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 118d28d..2699cc0 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -7,6 +7,11 @@ but this file may sometimes contain later improvements (e.g. typo fixes). ## next (not yet released) +- Error responses with non-200 HTTP status codes are now supported, + as long as the `MediaWiki-API-Error` response header is present + to indicate that the response represents a regular error and not an internal error. + (The status code is ignored; + the response body is expected to contain a response with one or more regular errors.) - Updated dependencies. ## v0.8.1 (2023-11-12) diff --git a/core.js b/core.js index 01a7ca0..6cf5a3f 100644 --- a/core.js +++ b/core.js @@ -557,7 +557,7 @@ class Session { body, } = internalResponse; - if ( status !== 200 ) { + if ( status !== 200 && !( 'mediawiki-api-error' in responseHeaders ) ) { throw new Error( `API request returned non-200 HTTP status code: ${ status }` ); } diff --git a/test/unit/core.test.js b/test/unit/core.test.js index e2c2d9b..76ff1fb 100644 --- a/test/unit/core.test.js +++ b/test/unit/core.test.js @@ -86,7 +86,17 @@ describe( 'Session', () => { await session.request( params ); } ); - it( 'throws on non-200 status', async () => { + it( 'supports non-200 status with mediawiki-api-error response header', async () => { + const session = singleRequestSession( { action: 'query' }, { + status: 404, + headers: { 'mediawiki-api-error': 'some-not-found-error' }, + body: { error: { code: 'some-not-found-error' } }, + } ); + await expect( session.request( { action: 'query' } ) ) + .to.be.rejectedWith( ApiErrors ); + } ); + + it( 'throws on non-200 status without mediawiki-api-error response header', async () => { const session = singleRequestSession( { action: 'query' }, { status: 502, body: 'irrelevant',