gpt4 book ai didi

javascript - 正确捕获异步函数node.js

转载 作者:行者123 更新时间:2023-12-03 01:28:55 26 4
gpt4 key购买 nike

我的尝试是:

我的 server.js 有以下内容:

const app = express();
app.get('/*', loader(filePath, observer));

我尝试调用的文件有时会加载错误,这些错误会冒出 uncaughtExceptions 并重新启动服务器。我需要以某种方式捕获它

export default (htmlFilePath, observer) => async (req, res) => {
try {
.......
.......
.......

const markupStream = renderToNodeStream(
<Provider store={store}>
<ConnectedRouter history={history} location={context}>
<App/>
</ConnectedRouter>
</Provider>
);

if (context.url) {
return res.redirect(301, context.url)
}

return fs.createReadStream(htmlFilePath)
.pipe(htmlReplace('#root', markupStream))
.pipe(replaceStream('__SERVER_DATA__', serialize(store.getState())))
.pipe(res);
} catch (err) {
const errMarkup = renderToNodeStream(
<Provider store={store}>
<ConnectedRouter history={history} location={context}>
<Error500 error={err}/>
</ConnectedRouter>
</Provider>
);

logger.log({
level: 'error',
message: `Rendering ${req.originalUrl} fallback to Error render method`,
...{
errorMessage: err.message,
stack: err.stack
}
});

return fs.createReadStream(htmlFilePath)
.pipe(htmlReplace('#root', errMarkup))
.pipe(res.status(500));
} finally {
logger.info(`Request finished ${req.originalUrl} :: ${res.statusCode}`)
end({ route: path, componentName: componentNames[0], code: res.statusCode })
logger.profile(profileMsg);
}
}

正确的做法是什么?在执行 ().catch(err 之前,我的问题是我总是遇到 uncaughtException,它从未进入 try{} 中的 catch > 函数内的 catch{}

最佳答案

使用 async 快速中间件时,为了捕获任何拒绝并将该拒绝传递给快速错误处理程序,您需要一个包装器:

async-handler.js

const asyncHandler = fn => (req, res, next) => {
return Promise
.resolve(fn(req, res, next))
.catch(next);
};

module.exports = asyncHandler;

ssr-stream.js

const ssrStream = (htmlFilePath, observer) => async (req, res) => {
// If you wrap this middleware with asyncHandler
// No need try/catch, you can let it bubble up, and it will go to express error middleware
// Of course you can do it, and handle the custom error here, and let it bubble up for generic errors.
}

export default ssrStream;

index.js

const app = express();
const asyncHandler = require('./async-handler');
const loader = require('./ssr-stream');

// Wrap your async function, with asyncHandler
app.get('/foo', asyncHandler(async(req, res) => {
throw new Error('Foo'); // This will go to the express error middleware
}));

app.get('/*', asyncHandler(loader(filePath, observer)));

app.use((err, req, res, next) => {

// Handle the error type, and set the correct status code
const status = 500;
res
.status(status)
.end(err.message);
});

关于javascript - 正确捕获异步函数node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51382989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com