猿问

fetch 将 ReadableStream 作为错误主体返回。如何获取该流的内容?

我正在使用 ODATA NPM 包通过 REST 调用获取 ODATA。(我认为这基本上只是 fetch 的包装器)。


好吧,我正在使用 await/try/catch 来获取错误,并且我想获取错误的正文。一定有比我正在做的更好的方法:


如果我这样做:


const setOperations = (async (jobNum) => {

    let reply = {}

    let payload = { ...OpData }

    payload.JobNum = jobNum

    try {

        reply = await o(JOBURL, options).post('JobOpers', payload).query()

    } catch (error) {

        console.log(`Error Code: ${error.status}`)

        console.log(`Error URL: ${error.url}`)

        const reader = error.body.getReader()

        const text =  await reader.read()

        console.log(`Error body: ${text.value}`)

    }

    return reply

})

那么显示的 text.value 就是一个 Uint8Array 字节流:


Error Code: 400

ERPStore.js:219 Error URL: https://pwsepicorapp.mycorp.com/ERP10.2Test/api/v1/Erp.BO.JobEntrySvc/JobOpers

ERPStore.js:222 Error body: 123,34,72,116,116,112,83,116,97,116,117,115,34,58,52,48,48,44,34,82,101,97,115,111,110,80,104,114,97,115,101,34,58,34,82,69,83,84,32,65,80,73,32,69,120,99,101,112,116,105,111,110,34,44,34,69,114,114,111,114,77,101,115,115,97,103,101,34,58,34,79,112,101,114,97,116,105,111,110,32,114,101,102,101,114,101,110,99,101,115,32,105,110,118,97,108,105,100,32,118,97,108,117,101,46,34,44,34,69,114,114,111,114,84,121,112,101,34,58,34,73,99,101,46,67,111,109,109,111,110,46,66,117,115,105,110,101,115,115,79,98,106,101,99,116,69,120,99,101,112,116,105,111,110,34,44,34,69,114,114,111,114,68,101,116,97,105,108,115,34,58,91,123,34,77,101,115,115,97,103,101,34,58,34,79,112,101,114,97,116,105,111,110,32,114,101,102,101,114,101,110,99,101,115,32,105,110,118,97,108,105,100,32,118,97,108,117,101,4

我想看到的是一个 JSON 对象,因为这就是这个字节流所对应的。


智慧大石
浏览 261回答 1
1回答

慕容708150

我需要另一个等待来读取错误:/** * EPICOR invoke ODATA Post command * @param {string} serviceBO - Busines Object that provides service * @param {string} args - the ODATA command and any arguments * @param {json} payload - and data to send in POST * @return {string} The next job number * @public */const post = (async (serviceBO, args, payload) => {    let reply = {}    const url = SERVERURL + serviceBO    const options = window.STORE.getState().identity.options    try {        reply = await o(url, options).post(args, payload).query()    } catch (error) {        console.log(`Error Code: ${error.status}`)        console.log(`Error URL: ${error.url}`)        const json = await error.json()        const body  = JSON.stringify(json, ' ', 4)        console.log(`Error body: ${body}`)        return error    }    return reply})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答