avoid error when logging invalid response error (#75757)

This commit is contained in:
Pierre Gayvallet 2020-08-24 18:25:02 +02:00 committed by GitHub
parent 3dea4444b9
commit 9fa43b4e47
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 40 additions and 5 deletions

View file

@ -157,6 +157,44 @@ describe('configureClient', () => {
`);
});
it('logs default error info when the error response body is empty', () => {
const client = configureClient(config, { logger, scoped: false });
let response = createApiResponse({
statusCode: 400,
headers: {},
body: {
error: {},
},
});
client.emit('response', new errors.ResponseError(response), response);
expect(loggingSystemMock.collect(logger).error).toMatchInlineSnapshot(`
Array [
Array [
"[ResponseError]: Response Error",
],
]
`);
logger.error.mockClear();
response = createApiResponse({
statusCode: 400,
headers: {},
body: {} as any,
});
client.emit('response', new errors.ResponseError(response), response);
expect(loggingSystemMock.collect(logger).error).toMatchInlineSnapshot(`
Array [
Array [
"[ResponseError]: Response Error",
],
]
`);
});
it('logs each queries if `logQueries` is true', () => {
const client = configureClient(
createFakeConfig({

View file

@ -21,7 +21,6 @@ import { stringify } from 'querystring';
import { Client } from '@elastic/elasticsearch';
import { Logger } from '../../logging';
import { parseClientOptions, ElasticsearchClientConfig } from './client_config';
import { isResponseError } from './errors';
export const configureClient = (
config: ElasticsearchClientConfig,
@ -39,10 +38,8 @@ const addLogging = (client: Client, logger: Logger, logQueries: boolean) => {
client.on('response', (error, event) => {
if (error) {
const errorMessage =
// error details for response errors provided by elasticsearch
isResponseError(error)
? `[${event.body.error.type}]: ${event.body.error.reason}`
: `[${error.name}]: ${error.message}`;
// error details for response errors provided by elasticsearch, defaults to error name/message
`[${event.body?.error?.type ?? error.name}]: ${event.body?.error?.reason ?? error.message}`;
logger.error(errorMessage);
}