Error management

Finally, we could manage the errors that could occur for any resource request:

  1. We will store the errors for each resource in a new remoteErrors object, which needs to be initialized:
      // Initialize data properties
initData.remoteErrors = {}
for (const key in resources) {
initData[key] = null
initData.remoteErrors[key] = null
}

The key of the remoteErrors object will be the same as the resource, and the value will be the error or null if there is no error.

Next, we need to modify the fetchResource method:

  • Before the request, reset the error by setting it to null
  • If there is an error in the catch block, put it into the remoteErrors object at the right key
  1. The fetchResource method should now look as follows:
      async fetchResource (key, url) {
this.$data.remoteDataLoading++
// Reset error
this.$data.remoteErrors[key] = null
try {
this.$data[key] = await this.$fetch(url)
} catch (e) {
console.error(e)
// Put error
this.$data.remoteErrors[key] = e
}
this.$data.remoteDataLoading--
},

We could now display specific error messages for each resource, but we will simply display a generic error message in this project. Let's add another computed property called hasRemoteErrors, which will return true if there is at least one error.

  1. Using the JavaScript Object.keys() method, we can iterate on the keys of the remoteErrors object and check if some values are not null (which means that they are truthy):
      computed: {
// ...

hasRemoteErrors () {
return Object.keys(this.$data.remoteErrors).some(
key => this.$data.remoteErrors[key]
)
},
},
  1. We can now change the FAQ component template again by replacing the error property with the new one:
      <div class="error" v-if="hasRemoteErrors">

Like we did before, you can shut down the server to see the error message displayed.

We have now finished the FAQ component, whose script should now look as follows:

<script>
import RemoteData from '../mixins/RemoteData'

export default {
mixins: [
RemoteData({
questionList: 'questions',
}),
],
}
</script>

As you can see, it is very concise now!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.160.61