When a request fails, you can catch a ApiRequestError, a ApiPartialResponseError or a ApiResponseError object (all instances of Error), that contain useful information about whats happening.
- An
ApiRequestErrorhappens when the request failed to sent (network error, bad URL...). - An
ApiPartialResponseErrorhappens the response has been partially sent, but the connection is closed (by you, the OS or Twitter). - An
ApiResponseErrorhappens when Twitter replies with an error.
Some properties are common for both objects:
erroristruetypecontains eitherETwitterApiError.Request,ETwitterApiError.PartialResponseorETwitterApiError.Response(depending of error)requestcontaining node's rawClientRequestinstance
requestError, an instance ofErrorthat has been thrown throughrequest.on('error')handler
responseError, an instance ofErrorthat has been thrown byresponse.on('error'), or by the tentative of parsing the result of a partial responseresponse, containing raw node'sIncomingMessageinstancerawContent, containing all the chunks received from distant server
data, containing parsed Twitter response data (type ofTwitterApiErrorData)codeis anumbercontaining the HTTP error code (401,404, ...)response, containing raw node'sIncomingMessageinstanceheaders, containingIncomingHttpHeadersrateLimit(can be undefined orTwitterRateLimit), containing parsed rate limit headers (if any)- (getter)
errors, direct access of parsed Twitter errors ((ErrorV1 | ErrorV2)[]orundefined) - (getter)
rateLimitError,trueif this error is fired because a rate limit has been hit - (getter)
isAuthError,trueif this error is fired because logged user cannot do this action (invalid token, invalid app rights...)
hasErrorCode(code: number | EApiV1ErrorCode | EApiV2ErrorCode): Tells if given Twitter error code is present in error response
Requests (that aren't used for streaming) natively support gzip/deflate compression.
If it causes issues, you can force compression to be disabled:
const client = new TwitterApi(tokens, { compression: false });If you want to debug a single request made through direct HTTP handlers .get/.post/.delete,
you can use an additional property named requestEventDebugHandler.
client.v1.get(
'statuses/user_timeline.json',
{ user_id: 10, count: 200 },
{ requestEventDebugHandler: (eventType, data) => console.log('Event', eventType, 'with data', data) },
)It takes a function of type (event: TRequestDebuggerHandlerEvent, data?: any) => void where available events are:
type TRequestDebuggerHandlerEvent = 'abort' | 'socket' | 'socket-error' | 'socket-connect'
| 'socket-close' | 'socket-end' | 'socket-lookup' | 'socket-timeout' | 'request-error'
| 'response' | 'response-aborted' | 'response-error' | 'response-close' | 'response-end';data parameter associated to events:
abort: None /abortevent ofrequestsocket:{ socket: Socket }/request.socketobject, when it is available throughrequest.on('socket')socket-error:{ socket: Socket, error: Error }/errorevent ofrequest.socketsocket-connect:{ socket: Socket }/connectevent ofrequest.socketsocket-close:{ socket: Socket, withError: boolean }/closeevent ofrequest.socketsocket-end:{ socket: Socket }/endevent ofrequest.socketsocket-lookup:{ socket: Socket, data: [err: Error?, address: string, family: string | number, host: string] }/lookupevent ofrequest.socketsocket-timeout:{ socket: Socket }/timeoutevent ofrequest.socketrequest-error:{ requestError: Error }/errorevent ofrequestresponse:{ res: IncomingMessage }/responseobject, when it is available throughrequest.on('response')response-aborted:{ error?: Error }/abortedevent ofresponseresponse-error:{ error: Error }/errorevent ofresponseresponse-close:{ data: string }(raw response data) /closeevent ofresponseresponse-end: None /endevent ofresponse
If you keep obtaining errors and you don't know how to obtain the response data, or you want to see exactly what have been sent to Twitter, you can enable the debug mode:
import { TwitterApiV2Settings } from 'twitter-api-v2';
TwitterApiV2Settings.debug = true;By default, all requests and responses will be printed to console.
You can customize the output by implementing your own debug logger:
// Here's the default logger:
TwitterApiV2Settings.logger = {
log: (msg, payload) => console.log(msg, payload),
};
// .logger follows this interface:
interface ITwitterApiV2SettingsLogger {
log(message: string, payload?: any): void;
}
// An example for a file logger
import * as fs from 'fs';
import * as util from 'util';
const destination = fs.createWriteStream('requests.log', { flags: 'a' });
TwitterApiV2Settings.logger = {
log: (msg, payload) => {
if (payload) {
const strPayload = util.inspect(payload);
destination.write(msg + ' ' + strPayload);
} else {
destination.write(msg);
}
},
};