First published in the Language finch documentation
preface
I used UMi-Request in my work. After searching in Baidu and Google, I found no more than 3 articles suitable and containing codes, so I had to practice and summarize by myself.
Umi-request is a little different
Unlike Axios & XHR, umi-Request is implemented based on fetch, so it only throws an error (i.e., catch) in the case of a network error, even if the interface returns an error such as 404/500. Umi-request provides an error handling function called errorHandler. All codes executed in umI-Request will be caught if an error is thrown.
Reference: github.com/umijs/umi-r… Error handling
Unified Exception Handling
The errorHandler example provided in the official document is relatively simple, which simply determines whether the thrown error error has a response attribute (for example, in the case of network error, there is no response attribute in error). This is prone to a problem: code execution error (such as not getting an external parameter), it also throws error without a response attribute… I think it is quite simple at present, mainly to make clear the following two points:
- Error capture sequence
- Customize Error and extend Error
Error capture sequence
- An error occurred
- ErrorHandler (is a Promise)
- If an error or reject is thrown, the next Promise catch is entered: request(“”,{}).then().catch()
- Otherwise enter the next Promise’s then: request(“”,{}).then()
Customize Error and extend Error
I hope to distinguish between the following types of errors:
- Network error
- HTTP error
- Interface error
- Other errors (such as code execution errors)
Use ES6 Class inheritance to encapsulate Error. Reference: useful. Javascript. The info/custom – erro…
subsequent
You can make it a little more complicated and customize the extension to distinguish between request and response errors, but it should all be the same.
Github
The code on Github is a complete set of my umi-request practice, not just umi- Request error handling