Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the network request and error handling of Ant Design Pro 5

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how Ant Design Pro 5 web requests and error handling are. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can gain something through the detailed introduction of this article.

The web request for Ant Design Pro 5 is a little complicated, and it's hard to figure out what's going on just by looking at the documentation and not reading the source code. Fetch umi-request @ umijs/plugin-request Ant Design Pro 5 related code is involved.

Fetch

Technology that replaces XMLHttpRequest's access to and manipulation of HTTP. The biggest problem with fetch is that an exception is thrown only when a network failure occurs or when a request is blocked; for cases such as a HTTP status code of 404 or 500, it is considered a normal response and does not throw an exception.

Reference: Fetch API

Umi-request

Based on fetch encapsulation, it provides functions such as caching, timeout, character encoding handling, error handling and so on. Error handling is closely related to development.

In order to solve the problem that fetch does not throw an exception under unsuccessful status codes, umi-request will determine whether the HTTP status code is 2xx; if not, an exception will be thrown. And the exception thrown by fetch itself is also handled, and more information is added to facilitate subsequent processing.

/ src/middleware/parseResponse.js

. then (body = > {. If (copy.status > = 200 & & copy.status

< 300) { // 提供源response, 以便自定义处理 if (getResponse) { ctx.res = { data: body, response: copy }; return; } ctx.res = body; return; } throw new ResponseError(copy, 'http error', body, req, 'HttpError'); }) .catch(e =>

{if (e instanceof RequestError | | e instanceof ResponseError) {throw e;} / A pair of unknown errors are processed const {req, res} = ctx; e.request = e.request | | req; e.response = e.response | | res; e.type = e.type | | e.name; e.data = e.data | | undefined; throw e;}).

Reference: umi-request

@ umijs/plugin-request

@ umijs/plugin-request is encapsulated on umi-request. Umi-request provides an error handling mechanism, while @ umijs/plugin-request provides regular error handling and prescribes the data format in which the server returns the response. UseRequest is also provided.

It is important to note that when referencing request, refer to @ umijs/plugin-request, not umi-request, otherwise you will find that the behavior of request is inconsistent with that described in the @ umijs/plugin-request document. The specific code is as follows:

/ / reference the request of umi-request. Wrong! Import request from 'umi-request';// refers to the reqeust of @ umijs/plugin-request. That's right. Import {request} from 'umi'; data format

The format of the data returned by the convention server is as follows:

Interface ErrorInfoStructure {success: boolean; / / if request is success data?: any; / / response data errorCode?: string; / / code for errorType errorMessage?: string; / / message display to user showType?: number; / / error display type: 0 silent; 1 message.warn; 2 message.error; 4 notification; 9 page traceId?: string; / / Convenient for back-end Troubleshooting: unique request ID host?: string; / / onvenient for backend Troubleshooting: host of current access server}

If the data returned by the server is inconsistent with this format, it can be adapted through configuration in Ant Design Pro 5/src/app.tsx. However, this adaptation only acts on error handling and affects the data returned by the interface. So this adaptation is not useful when using useRequest.

Export const request: RequestConfig = {errorConfig: {adaptor: (resData) = > {return {... resData, success: resData.ok, errorMessage: resData.message,};},},}

The returned data format has a success field that describes whether the request was successful or not. Umi-request throws an exception for responses other than http 2xx, so what's the use of success here? The answer is that http 2xx's request can also return success:false to artificially throw an exception.

However, we do not recommend this. The wrong request should return a response other than http 2xx, and umi-request will automatically throw an exception. So when adapting to the data structure, success can always be true.

/ umijs/plugins/blob/master/packages/plugin-request/src/request.ts

... Const errorAdaptor = requestConfig.errorConfig?.adaptor | (resData = > resData); / / Unified error handling of middleware / / the format of backend return {success: boolean, data: any} / / modify this part of the logic requestMethodInstance.use (async (ctx, next) = > {... Const errorInfo = errorAdaptor (resData, ctx); if (errorInfo.success = false) {/ / throw an error to errorHandler to handle const error: RequestError = new Error (errorInfo.errorMessage); error.name = 'BizError'; error.data = resData; error.info = errorInfo; throw error;}})

If the server returns data in a format, everything goes smoothly. But even for a normal response, the data must be wrapped in a data field, which feels a little awkward on both the back end and the front end. You generally want to return data directly in a normal response, and return a similar data format only if an error occurs.

Error handling

The above data format adaptation is also called when error handling, so it is not useless if success does not adapt false data. ShowType errorMessage errorCode is mainly obtained from data adaptation.

/ umijs/plugins/blob/master/packages/plugin-request/src/request.ts

Const errorAdaptor = requestConfig.errorConfig?.adaptor | (resData = > resData); requestMethodInstance = extend ({errorHandler: (error: RequestError) = > {/ / @ ts-ignore if (error?.request?.options?.skipErrorHandler) {throw error;} let errorInfo: ErrorInfoStructure | undefined If (error.name = = 'ResponseError' & & error.data & & error.request) {const ctx: Context = {req: error.request, res: error.response,}; errorInfo = errorAdaptor (error.data, ctx); error.message = errorInfo?.errorMessage | | error.message; error.data = error.data; error.info = errorInfo;} errorInfo = error.info If (errorInfo) {const errorMessage = errorInfo?.errorMessage; const errorCode = errorInfo?.errorCode; const errorPage = requestConfig.errorConfig?.errorPage | | DEFAULT_ERROR_PAGE; switch (errorInfo?.showType) {case ErrorShowType.SILENT: / / do nothing break; case ErrorShowType.WARN_MESSAGE: message.warn (errorMessage); break Case ErrorShowType.ERROR_MESSAGE: message.error (errorMessage); break; case ErrorShowType.NOTIFICATION: notification.open ({message: errorMessage,}); break Case ErrorShowType.REDIRECT: / / @ ts-ignore history.push ({pathname: errorPage, query: {errorCode, errorMessage},}); / / redirect to error page break; default: message.error (errorMessage); break }} else {message.error (error.message | | 'Request error, please retry.');} throw error;},... requestConfig,}); error display type

There are several values of the showType field in the data type, which can be displayed in different ways according to different error types with error handling methods.

Export enum ErrorShowType {SILENT = 0, / / No error WARN_MESSAGE = 1, / / warning message prompt ERROR_MESSAGE = 2, / / error message prompt NOTIFICATION = 4, / / Notification prompt REDIRECT = 9, / / Page Jump} useRequest

In the previous data format convention, useRequest acquires data from the data field in the response data by default. If the server returns data directly, you need to configure it in Ant Design Pro/config/config.ts:

Request: {dataField:',}

It should be noted that the data adaptation done above is invalid in useRequest, so don't think that everything will be all right if you do the data adaptation. Of course, there is no such annoyance when the server returns the data according to the previously agreed data format.

Paging data structure

Ant Design also has rules on the structure of paged data.

{list: [], current?: number, pageSize?: number, total?: number,}

If it does not conform to this format, you can configure it in the formatResult of useRequest. Such as:

Const {data, loading} = useRequest (() = > {return services.getUserList ('/ api/test');}, {formatResult: (result) = > {return...})

Reference:

@ umijs/plugin-request document

@ umijs/plugin-request source code

Ant Design Pro 5

Provides a custom error handling method, and an interface to customize the data format. The default demo code overrides the error handling of @ umijs/plugin-request. If you don't notice this, you will be confused that the error handling behavior of Ant Design Pro 5 is not consistent with that described in the @ umijs/plugin-request document, and the error display type described above is completely invalid.

Ant Design Pro/config/config.ts

Const errorHandler = (error: ResponseError) = > {const {response} = error; if (response & & response.status) {const errorText = codeMessage [response.status] | | response.statusText; const {status, url} = response; notification.error ({message: `request error ${status}: ${url} `, description: errorText,}) } if (! response) {notification.error ({description: 'your network failed to connect to the server', message: 'network exception',});} throw error;}; export const request: RequestConfig = {errorHandler,}. The above is what the Ant Design Pro 5 network request and error handling is like. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report