Skip to content

Commit

Permalink
feat(axios): nuxt friendly errors for SSR
Browse files Browse the repository at this point in the history
  • Loading branch information
Pooya Parsa committed Jun 9, 2017
1 parent 16f28b1 commit 65bc50f
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
2 changes: 1 addition & 1 deletion modules/axios/README.md
Expand Up @@ -4,7 +4,7 @@
- Automatically set base URL for client & server side
- Injects `$get`,`$post`,... into vue context instances so requests can be done easily.
- Exposes `setToken` function to `$axios` so we can easily and globally set authentication tokens.
- Throws *nuxt-friendly* exceptions.
- Throws *nuxt-friendly* exceptions and prevent SSR crashes.
- Automatically enables `withCredentials` when requesting to base URL.
- Automatically set request headers in SSR

Expand Down
34 changes: 28 additions & 6 deletions modules/axios/plugin.js
Expand Up @@ -63,7 +63,7 @@ export default (ctx) => {
const { app, store, redirect, req } = ctx

// Create new axios instance
const baseURL = process.env.browser
const baseURL = process.browser
? (process.env.API_URL_BROWSER || '<%= options.API_URL_BROWSER %>')
: (process.env.API_URL || '<%= options.API_URL %>')

Expand All @@ -82,13 +82,35 @@ export default (ctx) => {
return config
});
<% } %>
// Error handler
// Nuxt friendly error handler
axios.interceptors.response.use(undefined, (error) => {
if (error.response && error.response.status === 401) {
return redirect('/login')
if (error.response) {
// Error from backend (non 2xx status code)
if (error.response.status === 401) {
return redirect('/login')
}
error.statusCode = error.statusCode || parseInt(error.response.status) || 500
error.message = error.message || error.response.statusText || (error.statusCode + ' (Internal Server Error)')
} else if (error.request) {
// Error while making request
error.statusCode = error.statusCode || 500
error.message = error.message || 'request error'
} else {
// Something happened in setting up the request that triggered an Error
error.statusCode = 500
error.message = error.message || 'axios error'
}

// Display error page on unhandled promises
if(process.browser) {
return Promise.reject(error)
} else {
// Don't throw unhandled promises in SSR context
return app._nuxt.error.call({$options: app}, {
message: error.message,
statusCode: error.statusCode
})
}
console.log(error)
return Promise.reject(error)
});

// Make accessible using app.$axios
Expand Down

0 comments on commit 65bc50f

Please sign in to comment.