From 0d492c89fb918c9a4c1c6e69b6d4118c384d1408 Mon Sep 17 00:00:00 2001 From: "opensearch-trigger-bot[bot]" <98922864+opensearch-trigger-bot[bot]@users.noreply.github.com> Date: Thu, 7 Nov 2024 14:24:19 -0800 Subject: [PATCH] [Discover] fix error construction and retrieving status (#8807) (#8820) (cherry picked from commit 016f09055154770d4b25d4773051aa024fcbe901) Signed-off-by: Joshua Li Signed-off-by: github-actions[bot] Co-authored-by: github-actions[bot] --- .../query_enhancements/common/utils.test.ts | 28 +++++++++++++++++++ .../query_enhancements/common/utils.ts | 2 +- .../query_enhancements/server/routes/index.ts | 2 +- 3 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 src/plugins/query_enhancements/common/utils.test.ts 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 00000000000..39bbdc258be --- /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 2ac1cf430f5..9b2bb9e3aac 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 dd17231adee..79b93a27927 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, }); }