Skip to content

Commit 13705e8

Browse files
authored
fix(errors): match v2 problem types, explain X's errors, reject cut responses (#652)
EApiV2ErrorCode values are the problem types X returns again, and hasErrorCode compares them by their last part, on the whole error and on its errors array, so the api.twitter.com and api.x.com forms both match. Error messages now include the title and detail of v2 errors without an errors array, without '(see about:blank)'. TwitterApi.getErrors returns [] for an error with an empty or non-JSON body. A response cut before its end now rejects with ApiPartialResponseError whatever its parse mode, instead of resolving when the received part could be parsed as text or a buffer.
1 parent 09e2050 commit 13705e8

6 files changed

Lines changed: 126 additions & 53 deletions

File tree

‎doc/errors.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ Some properties are common for both objects:
1515
- `requestError`, an instance of `Error` that has been thrown through `request.on('error')` handler
1616

1717
## Specific properties of `ApiPartialResponseError`
18-
- `responseError`, an instance of `Error` that has been thrown by `response.on('error')`, or by the tentative of parsing the result of a partial response
18+
- `responseError`, an instance of `Error` that has been thrown by `response.on('error')` or by the tentative of parsing the response body, or that tells that the connection was closed before the end of the response
1919
- `response`, containing raw node's `IncomingMessage` instance
2020
- `rawContent`, containing all the chunks received from distant server
2121

@@ -30,7 +30,7 @@ Some properties are common for both objects:
3030
- (getter) `isAuthError`, `true` if this error is fired because logged user cannot do this action (invalid token, invalid app rights...)
3131

3232
## Specific methods of `ApiResponseError`
33-
- `hasErrorCode(code: number | EApiV1ErrorCode | EApiV2ErrorCode)`: Tells if given Twitter error code is present in error response
33+
- `hasErrorCode(code: number | EApiV1ErrorCode | EApiV2ErrorCode)`: Tells if given Twitter error code is present in error response. v2 problem types are compared by their last part (like `invalid-request`), so the `https://api.twitter.com/2/problems/…` and `https://api.x.com/2/problems/…` forms match each other
3434

3535
## Compression
3636

‎src/client-mixins/request-handler.helper.ts‎

Lines changed: 21 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,16 @@ export class RequestHandlerHelper<T> {
8080
.join(', ');
8181
}
8282

83-
protected formatV2Error(error: ErrorV2) {
84-
return `${error.title}: ${error.detail} (see ${error.type})`;
83+
protected formatV2Error({ title, detail, type }: Partial<ErrorV2>) {
84+
// X often repeats the title as detail, like in 'Unauthorized: Unauthorized'
85+
let message = [title, detail !== title ? detail : undefined].filter(Boolean).join(': ');
86+
87+
// 'about:blank' means that the HTTP code says it all
88+
if (type && type !== 'about:blank') {
89+
message += ` (see ${type})`;
90+
}
91+
92+
return message;
8593
}
8694

8795
protected createResponseError({ res, data, rateLimit, code }: IBuildErrorParams): ApiResponseError {
@@ -92,15 +100,14 @@ export class RequestHandlerHelper<T> {
92100

93101
// Errors formatting.
94102
let errorString = `Request failed with code ${code}`;
95-
if (data?.errors?.length) {
96-
const errors = data.errors as (ErrorV1 | ErrorV2)[];
103+
const errors = data?.errors as (ErrorV1 | ErrorV2)[] | undefined;
97104

98-
if (typeof errors[0] === 'object' && 'code' in errors[0]) {
99-
errorString += ' - ' + this.formatV1Errors(errors as ErrorV1[]);
100-
}
101-
else {
102-
errorString += ' - ' + this.formatV2Error(data as ErrorV2);
103-
}
105+
if (errors?.length && typeof errors[0] === 'object' && 'code' in errors[0]) {
106+
errorString += ' - ' + this.formatV1Errors(errors as ErrorV1[]);
107+
}
108+
// v2 errors explain themselves in title and detail, with or without an errors array
109+
else if (data?.title || data?.detail) {
110+
errorString += ' - ' + this.formatV2Error(data as ErrorV2);
104111
}
105112

106113
return new ApiResponseError(errorString, {
@@ -248,7 +255,7 @@ export class RequestHandlerHelper<T> {
248255
// Register the response data
249256
dataStream.on('data', chunk => this.responseData.push(chunk));
250257
dataStream.on('end', this.onResponseEndHandler.bind(this, resolve, reject));
251-
dataStream.on('close', this.onResponseCloseHandler.bind(this, resolve, reject));
258+
dataStream.on('close', this.onResponseCloseHandler.bind(this, reject));
252259

253260
if (dataStream !== res) {
254261
// A body that can't be decompressed, or a response cut midway, never emits 'end' on the decompressor
@@ -296,21 +303,11 @@ export class RequestHandlerHelper<T> {
296303
});
297304
}
298305

299-
protected onResponseCloseHandler(resolve: TResponseResolver<T>, reject: TResponseRejecter) {
306+
protected onResponseCloseHandler(reject: TResponseRejecter) {
300307
const res = this.res;
301308

302-
if (res.aborted) {
303-
// Try to parse the request (?)
304-
try {
305-
this.getParsedResponse(this.res);
306-
// Ok, try to resolve normally the request
307-
return this.onResponseEndHandler(resolve, reject);
308-
} catch (e) {
309-
// Parse error, just drop with content
310-
return reject(this.createPartialResponseError(e as Error, true));
311-
}
312-
}
313-
if (!res.complete) {
309+
// A cut response may still parse, as text, a buffer or even JSON, but it isn't the whole response
310+
if (res.aborted || !res.complete) {
314311
return reject(this.createPartialResponseError(
315312
new Error('Response has been interrupted before response could be parsed.'),
316313
true,

‎src/client/index.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,15 @@ export class TwitterApi extends TwitterApiReadWrite {
4848

4949
/* Static helpers */
5050
public static getErrors(error: any) {
51-
if (typeof error !== 'object')
51+
if (typeof error !== 'object' || !error)
5252
return [];
5353

54-
if (!('data' in error))
54+
// A response with an empty or non-JSON body has no errors to give
55+
const data = (error as TwitterApiError).data;
56+
if (typeof data !== 'object' || !data)
5557
return [];
5658

57-
return (error as TwitterApiError).data.errors ?? [];
59+
return data.errors ?? [];
5860
}
5961

6062
/** Extract another image size than obtained in a `profile_image_url` or `profile_image_url_https` field of a user object. */

‎src/types/errors.types.ts‎

Lines changed: 42 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,11 @@ interface IBuildApiResponseError {
164164
rateLimit?: TwitterRateLimit;
165165
}
166166

167+
/** Last part of a v2 problem type, like `invalid-request`, the same on the api.twitter.com and api.x.com hosts */
168+
function getProblemName(type: unknown) {
169+
return typeof type === 'string' ? type.split(/[/#]/).pop() : undefined;
170+
}
171+
167172
export class ApiResponseError extends ApiError implements TwitterApiError, IBuildApiResponseError {
168173
protected _options: any;
169174

@@ -212,20 +217,20 @@ export class ApiResponseError extends ApiError implements TwitterApiError, IBuil
212217
hasErrorCode(...codes: (EApiV1ErrorCode | number)[] | (EApiV2ErrorCode | string)[]) {
213218
const errors = this.errors;
214219

215-
// No errors
216-
if (!errors?.length) {
217-
return false;
218-
}
219-
220220
// v1 errors
221-
if ('code' in errors[0]) {
221+
if (errors?.length && 'code' in errors[0]) {
222222
const v1errors = errors as ErrorV1[];
223223
return v1errors.some(error => (codes as number[]).includes(error.code));
224224
}
225225

226-
// v2 error
227-
const v2error = this.data as ErrorV2;
228-
return (codes as string[]).includes(v2error.type);
226+
// v2 errors: X gives a problem type to the whole error, to the items of its errors array, or to both
227+
const v2errors = [this.data, ...(errors ?? [])] as Partial<ErrorV2>[];
228+
const problems = (codes as string[]).map(getProblemName);
229+
230+
return v2errors.some(error => {
231+
const problem = getProblemName(error?.type);
232+
return problem !== undefined && problems.includes(problem);
233+
});
229234
}
230235

231236
get errors(): (ErrorV1 | ErrorV2)[] | undefined {
@@ -336,25 +341,40 @@ export enum EApiV1ErrorCode {
336341
OobOauthIsNotAllowed = 417,
337342
}
338343

344+
/**
345+
* Problem types of v2 errors, as given by X in the `type` of an error.
346+
*
347+
* X has given them on several hosts (api.twitter.com, api.x.com), so `hasErrorCode` only compares their last part.
348+
*/
339349
export enum EApiV2ErrorCode {
340350
// Request errors
341-
InvalidRequest = 'https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-request',
342-
ClientForbidden = 'https://developer.x.com/en/support/x-api/error-troubleshooting#client-forbidden',
343-
UnsupportedAuthentication = 'https://developer.x.com/en/support/x-api/error-troubleshooting#unsupported-authentication',
351+
InvalidRequest = 'https://api.x.com/2/problems/invalid-request',
352+
ClientForbidden = 'https://api.x.com/2/problems/client-forbidden',
353+
UnsupportedAuthentication = 'https://api.x.com/2/problems/unsupported-authentication',
344354

345355
// Stream rules errors
346-
InvalidRules = 'https://developer.x.com/en/support/x-api/error-troubleshooting#invalid-rules',
347-
TooManyRules = 'https://developer.x.com/en/support/x-api/error-troubleshooting#rule-cap',
348-
DuplicatedRules = 'https://developer.x.com/en/support/x-api/error-troubleshooting#duplicate-rules',
356+
InvalidRules = 'https://api.x.com/2/problems/invalid-rules',
357+
TooManyRules = 'https://api.x.com/2/problems/rule-cap',
358+
RuleTooLong = 'https://api.x.com/2/problems/rule-length',
359+
DuplicatedRules = 'https://api.x.com/2/problems/duplicate-rules',
349360

350361
// Twitter errors
351-
RateLimitExceeded = 'https://developer.x.com/en/support/x-api/error-troubleshooting#usage-capped',
352-
ConnectionError = 'https://developer.x.com/en/support/x-api/error-troubleshooting#streaming-connection',
353-
ClientDisconnected = 'https://developer.x.com/en/support/x-api/error-troubleshooting#client-disconnected',
354-
TwitterDisconnectedYou = 'https://developer.x.com/en/support/x-api/error-troubleshooting#operational-disconnect',
362+
RateLimitExceeded = 'https://api.x.com/2/problems/rate-limit-exceeded',
363+
UsageCapped = 'https://api.x.com/2/problems/usage-capped',
364+
InternalError = 'https://api.x.com/2/problems/internal-error',
365+
ConnectionError = 'https://api.x.com/2/problems/streaming-connection',
366+
ClientDisconnected = 'https://api.x.com/2/problems/client-disconnected',
367+
TwitterDisconnectedYou = 'https://api.x.com/2/problems/operational-disconnect',
355368

356369
// Resource errors
357-
ResourceNotFound = 'https://developer.x.com/en/support/x-api/error-troubleshooting#resource-not-found',
358-
ResourceUnauthorized = 'https://developer.x.com/en/support/x-api/error-troubleshooting#not-authorized-for-resource',
359-
DisallowedResource = 'https://developer.x.com/en/support/x-api/error-troubleshooting#disallowed-resource',
370+
ResourceNotFound = 'https://api.x.com/2/problems/resource-not-found',
371+
ResourceUnauthorized = 'https://api.x.com/2/problems/not-authorized-for-resource',
372+
ResourceUnavailable = 'https://api.x.com/2/problems/resource-unavailable',
373+
DisallowedResource = 'https://api.x.com/2/problems/disallowed-resource',
374+
RecipientNotMessageable = 'https://api.x.com/2/problems/recipient-not-messageable',
375+
376+
// Field errors
377+
FieldUnauthorized = 'https://api.x.com/2/problems/field-unauthorized',
378+
NotAuthorizedForField = 'https://api.x.com/2/problems/not-authorized-for-field',
379+
FieldHydrationFailure = 'https://api.x.com/2/problems/field-hydration-failure',
360380
}

‎test/errors.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import 'mocha';
22
import { expect } from 'chai';
3-
import { ApiResponseError, EApiV1ErrorCode } from '../src';
3+
import { ApiResponseError, EApiV1ErrorCode, EApiV2ErrorCode, TwitterApi } from '../src';
44
import { FakeX, FakeXReply } from './fake-x';
55

66
describe('Error responses of X (offline: a fake X answers)', () => {
@@ -28,12 +28,32 @@ describe('Error responses of X (offline: a fake X answers)', () => {
2828

2929
expect(error).to.deep.include({ code: 403, data: body, isAuthError: false, rateLimitError: false });
3030
expect(error.headers['content-type']).to.equal('application/json; charset=utf-8');
31+
expect(error.message).to.equal('Request failed with code 403 - Forbidden: You are not permitted to perform this action.');
32+
});
33+
34+
it('Should explain and match v2 problem types, whatever the host X gives them on', async () => {
35+
const forbidden = await errorOf({
36+
status: 403,
37+
body: { title: 'Client Forbidden', detail: 'This request must be made using an approved developer account that is enrolled in the requested endpoint.', reason: 'client-not-enrolled', type: 'https://api.twitter.com/2/problems/client-forbidden' },
38+
});
39+
expect(forbidden.message).to.equal('Request failed with code 403 - Client Forbidden: This request must be made using an approved developer account that is enrolled in the requested endpoint. (see https://api.twitter.com/2/problems/client-forbidden)');
40+
expect(forbidden.hasErrorCode(EApiV2ErrorCode.ClientForbidden)).to.equal(true);
41+
expect(forbidden.hasErrorCode(EApiV2ErrorCode.InvalidRequest, EApiV2ErrorCode.ResourceNotFound)).to.equal(false);
42+
expect(forbidden.hasErrorCode(EApiV1ErrorCode.AuthenticationFail)).to.equal(false);
43+
44+
// A type given only in the errors array
45+
const disconnected = await errorOf({
46+
status: 400,
47+
body: { errors: [{ title: 'operational-disconnect', detail: 'This stream has been disconnected upstream for operational reasons.', type: 'https://api.x.com/2/problems/operational-disconnect' }] },
48+
});
49+
expect(disconnected.hasErrorCode(EApiV2ErrorCode.TwitterDisconnectedYou)).to.equal(true);
3150
});
3251

3352
it('Should flag authentication errors', async () => {
3453
const error = await errorOf({ status: 401, body: { title: 'Unauthorized', type: 'about:blank', status: 401, detail: 'Unauthorized' } });
3554

3655
expect(error.isAuthError).to.equal(true);
56+
expect(error.message).to.equal('Request failed with code 401 - Unauthorized');
3757
});
3858

3959
it('Should flag rate limit errors, with the limit and its reset time', async () => {
@@ -64,12 +84,23 @@ describe('Error responses of X (offline: a fake X answers)', () => {
6484

6585
expect(error.errors).to.deep.equal(errors);
6686
expect(error.message).to.include('Invalid Request: One or more parameters to your request was invalid.');
87+
expect(error.hasErrorCode(EApiV2ErrorCode.InvalidRequest)).to.equal(true);
88+
expect(error.hasErrorCode('https://api.twitter.com/2/problems/invalid-request')).to.equal(true);
6789
});
6890

6991
it('Should keep a body that is not JSON', async () => {
7092
const error = await errorOf({ status: 503, headers: { 'content-type': 'text/html' }, body: '<html>Over capacity</html>' });
7193

7294
expect(error).to.deep.include({ code: 503, data: '<html>Over capacity</html>' });
95+
expect(TwitterApi.getErrors(error)).to.deep.equal([]);
96+
});
97+
98+
it('Should give no errors for an empty body', async () => {
99+
const error = await errorOf({ status: 503, headers: { 'content-type': 'application/problem+json' }, body: '' });
100+
101+
expect(error).to.deep.include({ code: 503, data: undefined, message: 'Request failed with code 503' });
102+
expect(TwitterApi.getErrors(error)).to.deep.equal([]);
103+
expect(TwitterApi.getErrors(null)).to.deep.equal([]);
73104
});
74105

75106
it('Should resolve with the errors of a partly successful response', async () => {

‎test/request-handler.socket.test.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { ApiPartialResponseError, ApiRequestError } from '../src';
66
import RequestHandlerHelper from '../src/client-mixins/request-handler.helper';
77

88
describe('Request handler with a local keep-alive server (offline: no network or credentials needed)', () => {
9-
let mode: 'ok' | 'drop' | 'cut' | 'hang' = 'ok';
9+
let mode: 'ok' | 'drop' | 'cut' | 'cut-text' | 'until-close' | 'hang' = 'ok';
1010
let connections = 0;
1111

1212
const server = http.createServer((req, res) => {
@@ -19,6 +19,16 @@ describe('Request handler with a local keep-alive server (offline: no network or
1919
res.setHeader('content-type', 'application/json');
2020
res.write('{"data":');
2121
setTimeout(() => req.socket.destroy(), 10);
22+
} else if (mode === 'cut-text') {
23+
res.setHeader('content-type', 'text/plain');
24+
res.write('{"id":"1"}\n{"id":"2"}');
25+
setTimeout(() => req.socket.destroy(), 10);
26+
} else if (mode === 'until-close') {
27+
// No content-length nor chunks: the body ends when the server closes the connection
28+
res.useChunkedEncodingByDefault = false;
29+
res.setHeader('content-type', 'text/plain');
30+
res.write('{"id":"1"}\n');
31+
setTimeout(() => res.end('{"id":"2"}'), 10);
2232
}
2333
// 'hang': never answer
2434
}).on('connection', () => connections++);
@@ -76,6 +86,19 @@ describe('Request handler with a local keep-alive server (offline: no network or
7686
expect(error).to.be.instanceOf(ApiPartialResponseError);
7787
});
7888

89+
it('Should reject when a response that is not JSON is cut midway', async () => {
90+
mode = 'cut-text';
91+
92+
const error = await request().then(() => null, (e: Error) => e);
93+
expect(error).to.be.instanceOf(ApiPartialResponseError);
94+
});
95+
96+
it('Should resolve with a body that ends when the server closes the connection', async () => {
97+
mode = 'until-close';
98+
99+
expect(await request()).to.deep.include({ data: '{"id":"1"}\n{"id":"2"}' });
100+
});
101+
79102
it('Should reject on timeout, then keep working', async () => {
80103
mode = 'hang';
81104

0 commit comments

Comments
 (0)