为什么反应组件没有捕获公理错误



我在使用flask 的python上有以下代码

@bp.route("/test", methods=["GET"])
def test():

throw_error = True
if throw_error : 
return jsonify(message="Throwing an error"), 405

return jsonify(message="Test message"), 200

在React上,我有一个上下文设置,具有以下功能

function testRequest(){
const response = axios.get('/api/test')
console.log(response)
}

我在的另一个组件中点击按钮时调用这个函数

async function handleButtonClick(e){
e.preventDefault();
try{
await testRequest(); 
}catch(error) { // DOESN'T EXECUTE??
console.error("Error occured")
setError("Error occurred in test method")
}
}

为什么不是try-catch,捕获405错误?

你只能有效地等待承诺。testRequest不返回承诺。

它触发axios.get,将promise分配给response,记录它,然后返回undefined

try/catch根本没有触及承诺。

你可以用来解决这个问题

function testRequest(){
const response_promise = axios.get('/api/test')
console.log(response_promise)
return response_promise;
}

因此,承诺是在try/catch内部await

通过以下对函数的修改,您将能够捕获错误。

async function testRequest() {
const response = await axios.get('http://localhost:1337/sample/test');
return response;
}

async function handleButtonClick(e:any) {
e.preventDefault();
try {
await testRequest();
} catch (error) { // DOESN'T EXECUTE??
console.error("Error occured")
console.log(error.mes);
}
}

最新更新