diff --git a/.changeset/gentle-requests-return.md b/.changeset/gentle-requests-return.md new file mode 100644 index 000000000..9d864d358 --- /dev/null +++ b/.changeset/gentle-requests-return.md @@ -0,0 +1,5 @@ +--- +'@vben/request': patch +--- + +fix: preserve response metadata when requests fail diff --git a/packages/effects/request/src/request-client/request-client.test.ts b/packages/effects/request/src/request-client/request-client.test.ts index 661753496..d3f9bd158 100644 --- a/packages/effects/request/src/request-client/request-client.test.ts +++ b/packages/effects/request/src/request-client/request-client.test.ts @@ -2,6 +2,10 @@ import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + defaultResponseInterceptor, + errorMessageResponseInterceptor, +} from './preset-interceptors'; import { RequestClient } from './request-client'; describe('requestClient', () => { @@ -64,6 +68,38 @@ describe('requestClient', () => { }); }); + it('should preserve response metadata when an interceptor rejects', async () => { + requestClient.addResponseInterceptor( + defaultResponseInterceptor({ + codeField: 'code', + dataField: 'data', + successCode: 0, + }), + ); + requestClient.addResponseInterceptor(errorMessageResponseInterceptor()); + mock.onGet('/test/interceptor-error').reply(200, { + code: 1001, + data: null, + message: 'request failed', + }); + + await expect( + requestClient.get('/test/interceptor-error', { + responseReturn: 'data', + }), + ).rejects.toMatchObject({ + response: { + data: { + code: 1001, + data: null, + message: 'request failed', + }, + status: 200, + }, + status: 200, + }); + }); + it('should successfully upload a file', async () => { const fileData = new Blob(['file contents'], { type: 'text/plain' }); diff --git a/packages/effects/request/src/request-client/request-client.ts b/packages/effects/request/src/request-client/request-client.ts index 453913b27..d2715c0c0 100644 --- a/packages/effects/request/src/request-client/request-client.ts +++ b/packages/effects/request/src/request-client/request-client.ts @@ -146,18 +146,14 @@ class RequestClient { url: string, config: RequestClientConfig, ): Promise { - try { - const response: AxiosResponse = await this.instance({ - url, - ...config, - ...(config.paramsSerializer - ? { paramsSerializer: getParamsSerializer(config.paramsSerializer) } - : {}), - }); - return response as T; - } catch (error: any) { - throw error.response ? error.response.data : error; - } + const response: AxiosResponse = await this.instance({ + url, + ...config, + ...(config.paramsSerializer + ? { paramsSerializer: getParamsSerializer(config.paramsSerializer) } + : {}), + }); + return response as T; } }