diff --git a/src/plugins/query_enhancements/common/utils.test.ts b/src/plugins/query_enhancements/common/utils.test.ts new file mode 100644 index 000000000000..39bbdc258bea --- /dev/null +++ b/src/plugins/query_enhancements/common/utils.test.ts @@ -0,0 +1,28 @@ +/* + * Copyright OpenSearch Contributors + * SPDX-License-Identifier: Apache-2.0 + */ + +import { handleFacetError } from './utils'; + +describe('handleFacetError', () => { + const error = new Error('mock-error'); + (error as any).body = { + message: 'test error message', + }; + (error as any).status = '400'; + it('should throw an error with message from response.data.body.message', () => { + const response = { + data: error, + }; + + expect(() => handleFacetError(response)).toThrowError(); + try { + handleFacetError(response); + } catch (err: any) { + expect(err.message).toBe('test error message'); + expect(err.name).toBe('400'); + expect(err.status).toBe('400'); + } + }); +}); diff --git a/src/plugins/query_enhancements/common/utils.ts b/src/plugins/query_enhancements/common/utils.ts index 2ac1cf430f5c..9b2bb9e3aacf 100644 --- a/src/plugins/query_enhancements/common/utils.ts +++ b/src/plugins/query_enhancements/common/utils.ts @@ -43,7 +43,7 @@ export const removeKeyword = (queryString: string | undefined) => { }; export const handleFacetError = (response: any) => { - const error = new Error(response.data.body ?? response.data); + const error = new Error(response.data.body?.message ?? response.data.body ?? response.data); error.name = response.data.status ?? response.status ?? response.data.statusCode; (error as any).status = error.name; throw error; diff --git a/src/plugins/query_enhancements/server/routes/index.ts b/src/plugins/query_enhancements/server/routes/index.ts index dd17231adee2..79b93a279272 100644 --- a/src/plugins/query_enhancements/server/routes/index.ts +++ b/src/plugins/query_enhancements/server/routes/index.ts @@ -92,7 +92,7 @@ export function defineSearchStrategyRouteProvider(logger: Logger, router: IRoute error = err; } return res.custom({ - statusCode: error.status, + statusCode: error.status || err.status, body: err.message, }); }