我已经编写了一个API以在浏览器中查看服务器的日志。我尝试过但没有得到如何进行错误处理的信息。请说明如何处理错误。我是node.js的新手
app.get('/logs', function(request, response, next) {
res.sendFile('file', 'path');
});
最佳答案
错误处理如下所示。
app.get('/logs', async function(req, res) {
let something;
try {
something = await "file processing";
} catch (error) {
res.status(500).json({ error: error.toString() });
}
res.json({ something });
});
从其他端点获取API时,可以使用
promise
或async-await
当
try
语句出现问题时,将捕获错误如果您想故意出错,请在
new Error()
语句中使用try
您也可以在尝试处理路线错误时研究快速错误中间件。
关于node.js - 如何处理获取API请求的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54944241/