Nuxt.js: How to handle error in nuxtServerInit?

Created on 5 Feb 2018  路  8Comments  路  Source: nuxt/nuxt.js

async nuxtServerInit ({ commit, state }) {
    let sections = await axios.get(`http://api.example.com/sections`)
    commit('SET_SECTIONS', sections.data)
  }

Is there any way to handle this kind of error? I want to show user error page.
Docs says

The context is given to nuxtServerInit as the 2nd argument, it is the same as the data or fetch method except that context.redirect() and context.error() are omitted.

This question is available on Nuxt.js community (#c2406)

Most helpful comment

Use context.error, it should work now, I will discuss with team about the doc.

  nuxtServerInit({ commit }, { error }) {
    error('Error on [nuxtServerInit] action.')
  }

All 8 comments

You can wrap the method with a try catch and handle the error by yourself, only if the error is thrown, the error page will be shown

@clarkdo the reason I ask it's because error doesn't work.

context.error() are omitted

I tried try catch - no error page are shown. It just silently doesn't show anything.

async nuxtServerInit ({ commit }) {
    try {
      let sections = await axios.get(`http://api.example.com/sections`)
      commit('SET_SECTIONS', sections.data)
    } catch (err) {
      console.error('Error on [nuxtServerInit] action.', err)
    }
  }

Use context.error, it should work now, I will discuss with team about the doc.

  nuxtServerInit({ commit }, { error }) {
    error('Error on [nuxtServerInit] action.')
  }

I have talked to team, you can be free to use context.error now, we will update doc soon.

@clarkdo thank you, this is beautiful! Working like a charm. Error handling in Nuxt are super-cool.

Now the last thing bothers me about Error handling - is Error layout transition. I just can't find the solution how to make it work smoothly. I tried to switch modes but still Error layout appears on the page while Default layout is still leaving.

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vadimsg picture vadimsg  路  3Comments

pehbehbeh picture pehbehbeh  路  3Comments

gary149 picture gary149  路  3Comments

uptownhr picture uptownhr  路  3Comments

shyamchandranmec picture shyamchandranmec  路  3Comments