javascript - 消除由于不可预见的错误而导致的一组函数的不完整执行 (JavaScript)
问题描述
我仍在学习该语言,我很想知道当一个动作需要执行一系列函数时,确保所有函数都执行或不执行的正确方法是什么。例如,我可能有一个调用 apply() 函数的 HTML 按钮:
function apply() {
try {
// Check arguments, choose what exactly to do next through some IFs etc...
}
anotherFunction();
}
function anotherFunction() {
try {
// Request data from DB, process data received, update object variables, etc...
}
yetAnotherFunction();
}
function yetAnotherFunction() {
try {
// Update HTML
}
oneMoreFunction();
}
function oneMoreFunction() {
try {
// Update graph
}
}
所以这里的问题是,如果流程中的任何函数抛出错误,其余函数将不会做它们应该做的事情,因此整个 Apply 过程将被应用一些更改而中断(假设 HTML 正在更新)但是休息(图表)不是。我很想知道防止这种行为的最佳做法是什么?是的,我正在尽力使用 try {} 并检查参数是否有错误等,但看起来我无法预见一切,我只需要某种方式告诉代码“确保你可以执行所有函数,在万一出现任何错误,根本不做任何事情”。请告知在这里可以做什么?
解决方案
在考虑 try/catch 块时,您走的是正确的道路,但请注意我也使用了“catch”。通常(也许这是强制执行的,我不记得了)你需要 catch 块和 try 块。
所以你的函数可能看起来像这样:
function async myFirstTryCatch() {
try {
// Make your request in the try block
await requestCall();
} catch(error){
// Hey, my http call returned an error
// Deal with the error here. Maybe show a toast, validate a form
// Anything you need to not break the code and have good UX
console.log(error)
}
}
在同样的思路中,您可以让每个函数处理自己的 try/catch,或者在您的 apply 函数中控制它,以防某些链必须继续/停止相互依赖。
function apply() {
try {
firstCall();
functionThatRequiresFirstCalltoSucceed();
} catch (error){
//Will catch if either firstCall or functionThatRequiresFirstCalltoSucceed fail
console.log(error)
}
functionThatIndependsFromTheResultAbove();
}
我希望这将帮助您建立有关 JS 错误处理的想法 :)
重要提示 如果你的代码进入了catch块,它会认为错误已经被处理并且不会传播!这是一个例子
function functionThatThrowsError(){
try{
throw new Error('Example Error!');
} catch (error) {
// Error has been dealt with
console.log(error) // Returns "Example Error"
// throw error; <--- Throw the error in the catch block if you need t to propagate
}
}
function wontCatchError() {
try {
functionThatThrowsError();
} catch (error) {
// THE CODE WILL NOT ENTER THE CATCH BLOCK
// SINCE THE ERROR WAS CAUGHT IN THE FUNCTION ITSELF.
// If you need to catch here as well, make sure to throw the error
// in the catch block of the 'functionThatThrowsError'
console.log(error)
}
}
推荐阅读
- tensorflow - SSD 锚框相对于输入图像大小或特征图的比例
- javascript - Google Apps 脚本调用函数,该函数执行模态对话框,然后在用户进行选择后执行另一个函数
- reactjs - React Navigation:底部选项卡样式
- python-3.x - python scrape使用请求无法解析json
- sql - 无尽的日期列表生成器
- java - ListJoin 和 multiselect with criteriaquery with Polymorphism
- java - 如何在简单的 java 项目中设置 ELK
- html - VUE:如何在一个文件中包含多个组件部分?
- vectorization - 在 Arrayfire 中扩展间隔数组
- r - 使用ggplot2在R中组合堆叠条形图和折线图的问题