有什么方法可以在使用 await 时获取 4xx 响应主体 w/o try...catch?
Any way to get 4xx response body w/o try...catch while using await?
async function checkToken(token) {
const result = await superagent
.post(`${config.serviceUrl}/check_token`)
.send({token});
return result.body;
}
默认选项,如果此调用将 return 401 抛出异常,这不是我所期望的。 API 我调用的是使用 HTTP 状态消息也作为正文来返回信息,我只需要正文部分。
HTTP 状态 401 的响应是
{
"data": null,
"error": {
"code": "INVALID_TOKEN",
"message": "Token is not valid"
}
}
目前,为了得到这个,我需要用 try...catch
包装所有超级代理调用
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;
}
有什么方法可以使第一个示例正常工作并returning JSON w/o 查看 HTTP 状态?
试试这个
async function checkToken(token) {
const result = await superagent
.post(`${config.serviceUrl}/check_token`)
.send({token}).then(v=>v).catch(v=>v);
return result.body;
}
默认情况下,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
、returns中的函数为真则不会被认为是错误情况。
async function checkToken(token) {
const result = await superagent
.post(`${config.serviceUrl}/check_token`)
.send({token});
return result.body;
}
默认选项,如果此调用将 return 401 抛出异常,这不是我所期望的。 API 我调用的是使用 HTTP 状态消息也作为正文来返回信息,我只需要正文部分。
HTTP 状态 401 的响应是
{
"data": null,
"error": {
"code": "INVALID_TOKEN",
"message": "Token is not valid"
}
}
目前,为了得到这个,我需要用 try...catch
包装所有超级代理调用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;
}
有什么方法可以使第一个示例正常工作并returning JSON w/o 查看 HTTP 状态?
试试这个
async function checkToken(token) {
const result = await superagent
.post(`${config.serviceUrl}/check_token`)
.send({token}).then(v=>v).catch(v=>v);
return result.body;
}
默认情况下,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
、returns中的函数为真则不会被认为是错误情况。