2017-11-18 72 views
0
async function checkToken(token) { 
    const result = await superagent 
    .post(`${config.serviceUrl}/check_token`) 
    .send({token}); 
    return result.body; 
} 

默認選項,如果這個調用將返回401拋出異常,這不是我所期望的。我打電話給我的API使用HTTP狀態消息也作爲身體來提供信息,我只需要身體部分。任何方式來獲得4xx響應身體W/O嘗試...趕上,而使用等待?

,HTTP狀態爲401的響應是

{ 
    "data": null, 
    "error": { 
     "code": "INVALID_TOKEN", 
     "message": "Token is not valid" 
    } 
} 

而目前,爲了得到這一點,我需要包裝所有的SuperAgent與嘗試調用...趕上

async function checkToken(token) { 
    let result = null; 
    try { 
    result = await superagent 
     .post(`${config.serviceUrl}/check_token`) 
     .send({token}); 
    } catch (e) { 
    result = e.response; 
    } 
    return result.body; 
} 

任何方式有1樣品工作和返回JSON沒有看HTTP狀態?

回答

1

SuperAgent的默認對待每個4XX和5xx響應的錯誤。但是,您可以通過使用.ok來告訴它,您認爲哪些響應是錯誤的。從文檔(https://visionmedia.github.io/superagent/#error-handling

樣品例如,

request.get('/404') 
.ok(res => res.status < 500) 
.then(response => { 
    // reads 404 page as a successful response 
}) 

如果函數的.ok內,返回true,則它不會被認爲是錯誤的情況下。

0

試試這個

async function checkToken(token) { 
 
    const result = await superagent 
 
    .post(`${config.serviceUrl}/check_token`) 
 
    .send({token}).then(v=>v).catch(v=>v); 
 
    return result.body; 
 
}