【发布时间】:2021-09-21 12:44:54
【问题描述】:
我不确定我是否设置了我的快速控制器以正确返回正确的响应。当端点被命中时,我想用 axios 调用地址服务并返回数据,或者如果出错则返回响应。但是,目前如果找不到则返回默认错误400,但响应状态仍然是200。
这里是否有我遗漏的默认方法,或者这部分正确?
控制器
const getAddressWithPostcode = async (params: Params) => {
const { postCode, number } = params
const addressUrl = `${URL}/${postCode}${number
? `/${number}?api-key=${API_KEY}`
: `?api-key=${API_KEY}`}`
try {
const { data } = await axios.get(addressUrl)
return data
} catch (e) {
// throw e
const { response: { status, statusText } } = e
return {
service: 'Address service error',
status,
statusText,
}
}
}
const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
const { params } = req
await getAddressWithPostcode(params)
.then((data) => {
res.send(data).status(200)
})
.catch((e) => {
console.log('e', e)
next(e)
})
}
如果我发送一个狡猾的请求(使用邮递员),我会得到响应状态 200,但返回的数据是带有状态和文本的对象。我想将此作为我的默认响应,而不是返回具有这些属性的对象。 (见下图)。
这里只是一些方向会很好,可能是在 express 中使用 async await 和在内部使用外部 axios 调用时返回错误的最佳实践。
... ...
更新:
为此更新了我的代码,作为对答案的回应,我稍微重构了我的代码。
const getAddressWithPostcode = async (params: Params) => {
const { postCode, number } = params
const addressUrl = `${URL}/${postCode}${number
? `/${number}?api-keey=${API_KEY}`
: `?api-key=${API_KEY}`}`
try {
const { data } = await axios.get(addressUrl)
return data
} catch (e) {
// throw e
const { response } = e
return response
}
}
const findAddress = async (req: Request<Params>, res: Response, next: NextFunction) => {
const { params } = req
await getAddressWithPostcode(params)
.then((data) => {
console.log('data', data)
if (data.status !== 200) res.sendStatus(data.status)
else {
res.send(data)
}
})
.catch(err => {
console.log('err', err)
next(err)
})
}
【问题讨论】:
标签: javascript node.js typescript express error-handling