I tried using a catch
within the promise on client but it doesn't seem to pick up the error.
服务器:
pdf.create(pdfTemplate(transcriptAsObject), {}).toFile(`routes/api/${finalPdfName}`, (err) => {
if(err) {
res.send(Promise.reject());
}
res.send(Promise.resolve());
});
客户:
axios.post('/create-pdf', this.state)
.catch(err => console.log('error hit: ', err))
.then(() => axios.get('fetch-pdf', { responseType: 'blob' }))
.then((res) => {
const pdfBlob = new Blob([res.data], { type: 'application/pdf' });
saveAs(pdfBlob, 'newPdf.pdf');
})
.then(() => console.log('success brotha'))
首先,您应将.catch()放在.then()之后
如果在后端API中指定一个错误(例如,
You don't send promises to your client. So both your
res.send(Promise.resolve())
and yourres.send(Promise.resolve())
are not correct. Instead, you send a response with an appropriate status.例如,对于错误,您将执行以下操作:
然后,客户解释该状态并决定要做什么。如果您在服务器上遇到意外错误,通常会在发送回的响应中设置5xx状态,然后客户端代码可以看到该错误状态并做出相应的反应。
It is up to the client library that you're using for sending an Ajax call whether it makes a rejection out of a 5xx status or not. The
fetch()
interface built into the browser only makes a rejection out of true network error (no response coming back). Any response back from the server is considered a successful request from the point of view offetch()
. You will have to look and see how axios handles non-2xx response statuses, whether it makes it into a rejected promise for you or whether you have to explicitly check for the status in the.then()
handler.Looking at the axios documentation, it shows this default behavior:
这意味着除非状态为2xx,否则它将拒绝。因此,从服务器返回500状态将导致客户端请求中的axios拒绝。如果要修改axios中的此行为,则可以自定义。