Browse Source

fix(@vben/request): preserve response metadata on errors (#8377)

* fix(request): preserve response metadata on errors

* style(request): order interceptor test imports
pull/8383/head
俞可 · YU KE 3 weeks ago
committed by GitHub
parent
commit
3b377c178c
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 5
      .changeset/gentle-requests-return.md
  2. 36
      packages/effects/request/src/request-client/request-client.test.ts
  3. 20
      packages/effects/request/src/request-client/request-client.ts

5
.changeset/gentle-requests-return.md

@ -0,0 +1,5 @@
---
'@vben/request': patch
---
fix: preserve response metadata when requests fail

36
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' });

20
packages/effects/request/src/request-client/request-client.ts

@ -146,18 +146,14 @@ class RequestClient {
url: string,
config: RequestClientConfig,
): Promise<T> {
try {
const response: AxiosResponse<T> = 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<T> = await this.instance({
url,
...config,
...(config.paramsSerializer
? { paramsSerializer: getParamsSerializer(config.paramsSerializer) }
: {}),
});
return response as T;
}
}

Loading…
Cancel
Save