我在react应用程序中有以下代码(顶层文件-只是为了显示问题,我知道这不是进行api调用和检索数据的正确位置):
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
async function run() {
try {
return await fetch("https://somenonexistingplace.com");
} catch (e) {
console.error(e);
}
}
run();
ReactDOM.render(<App />, document.getElementById('root'));
当我运行这段代码时,catch显然缓存了异常,但显示'e is undefined‘-因此我无法访问通常存在于e. See screenshot from debug session中的错误消息。
当我在附加到html的纯脚本中在React应用程序之外运行这样的代码时,everything works fine和e是一个具有正确错误消息的对象。
唯一的区别是,第一个示例位于React应用程序中,而第二个示例位于React之外。
所以我的问题是:这里发生了什么,如何修复它?
编辑:我知道我可以用promises和.catch替换它(...)但这不是重点-我感兴趣的是为什么try/catch在这里不能像预期的那样工作。
发布于 2019-06-28 20:21:50
我建议将语法从try/catch改为fetch().catch()
return await fetch("https://somenonexistingplace.com").catch(e => console.error(e))
发布于 2019-06-28 20:23:17
try
/ catch
很棒,但它只适用于命令式代码。
从docs,
错误边界保留了React的声明性质,并按照您预期的方式运行。例如,即使由树中某处的setState导致的componentDidUpdate方法中出现错误,它仍然会正确地传播到最接近的错误边界。
举个例子,
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
用法,
<ErrorBoundary>
<YourComponent />
</ErrorBoundary>
发布于 2019-06-28 20:20:12
试试这个-->
URL='http://<--some wrong url -->'
async function run() {
const resp= await fetch(URL);
console.log(resp)
}
如果出现任何错误,它应该自动响应出现。
https://stackoverflow.com/questions/56806757
复制相似问题