简体   繁体   English

从服务器获取数据时,是否必须在所有脚本中写入 catch error?

[英]Do I have to write catch error in all script when fetching data from server?

I got some question about try, catch of data that is thrown from server using await.我有一些关于尝试捕获使用等待从服务器抛出的数据的问题。

for example例如

script A剧本A

try{
  let a = await get_user_data()
}
catch(err){
  console.log(err)
}

script B剧本B

try{
  let b = await get_something()
}
catch(err){
  console.log(err)
}

Let's just see we have a code like this to get user data, and another script to get something from the server.让我们看看我们有这样的代码来获取用户数据,还有另一个脚本来从服务器获取一些东西。 If the user token is expired, the two scripts will get 401 error(Logged in is required) and If no action is made, it will just end with it.如果用户令牌已过期,这两个脚本将出现 401 错误(需要登录),如果没有采取任何行动,它将以它结束。

So here's my question.所以这是我的问题。 Do I have to write all codes on each scripts to do some actions?我是否必须在每个脚本上编写所有代码才能执行某些操作? like if error.respond.status is 401 go to login page, if error.respond.status is 500 do something... Is there a better way to know the error has occured in App(.svelte)?就像如果 error.respond.status 是 401 go 登录页面,如果 error.respond.status 是 500 做一些事情......有没有更好的方法来知道 App(.svelte)中发生了错误? or something like global error variable?或类似全局错误变量的东西?

First of all, you don't have to use a try catch.首先,您不必使用 try catch。 But it makes sense to implement error handling.但是实现错误处理是有意义的。 If you have a try catch for every api call, I would take a different approach.如果您对每个 api 调用都有一个 try catch,我会采用不同的方法。 I would write a function that does the XHR.我会写一个 function 来执行 XHR。 You give the function only the endpoint, method and data.您只给 function 端点、方法和数据。 In this method you can do the error handling once.在这种方法中,您可以进行一次错误处理。 This way you would have it centrally in one place for all XHR calls with one error handling.这样一来,您可以将所有 XHR 调用集中在一个地方,并进行一次错误处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM