Permalink
Browse files

feat(axios): nuxt friendly errors for SSR

  • Loading branch information...
pi0 committed Jun 9, 2017
1 parent 16f28b1 commit 65bc50fd0bd4e6d3a784471e59e78e0c8b18aae3
Showing with 29 additions and 7 deletions.
  1. +1 −1 modules/axios/README.md
  2. +28 −6 modules/axios/plugin.js
@@ -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

@@ -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 %>')

@@ -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

0 comments on commit 65bc50f

Please sign in to comment.