VueJS HTTP request error 500 Handling

邮差的信 提交于 2019-12-24 09:17:18

问题


I am having this problem where I make HTTP Request to the API and in case of error ( specially error 500) the JS just breaks or goes into infinite loop and I should close the window and re-open the page. What I need is a message to pop up and in very generic way explain what happened. How should I handle this kind of error any ideas?

Example Request:

this.$http.get('people', { params }).then(({ data }) => {

            this.setFetching({
                fetching: false
            })
        })

回答1:


then accepts a second callback to handle errors. You can also supply a .catch in addition to a .then to handle more severe failures.

new Vue({
  el: '#app',
  data: {
    fetching: true
  },
  mounted() {
    this.$http.get('people')
      .then(() => {
          this.setFetching({
            fetching: false
          })
        },
        (err) => {
          console.log("Err", err);
        })
      .catch((e) => {
        console.log("Caught", e);
      })
  }
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue.resource/1.2.1/vue-resource.min.js"></script>
<div id="app">
</div>


来源:https://stackoverflow.com/questions/43092995/vuejs-http-request-error-500-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!