Permalink
Browse files

feat: responseInterceptor and errorHandler

  • Loading branch information...
pi0 committed Aug 30, 2017
1 parent 61432a1 commit b16d6bf8a3b8bd5f919674d9e65f9a256cc354d9
Showing with 39 additions and 8 deletions.
  1. +19 −0 README.md
  2. +20 −8 lib/plugin.template.js
@@ -144,6 +144,25 @@ requestInterceptor: (config, { store }) => {
}
```
### `responseInterceptor`
- Default: `null`
Function for manipulating axios responses.
### `errorHandler`
- Default: (Return promise rejection with error)
Function for custom global error handler.
This example uses nuxt default error page.
```js
axios: {
errorHandler (error) {
this.error('Request Error: ' + error)
}
},
```
## Helpers
### Fetch Style requests
@@ -31,7 +31,7 @@ const reqMethods = [
]
reqMethods.forEach(method => {
axiosExtraProto['$' + method] = function () {
return this[method].apply(this, arguments).then(res => res.data)
return this[method].apply(this, arguments).then(res => res && res.data)
}
})
@@ -60,13 +60,17 @@ function errorHandler(error) {
error.message = error.message || 'request error'
} else {
// Something happened in setting up the request that triggered an Error
error.statusCode = 500
error.statusCode = error.statusCode || 0
error.message = error.message || 'axios error'
}
return Promise.reject(error)
}
<% if (options.errorHandler) { %>
const customErrorHandler = <%= serialize(options.errorHandler).replace('errorHandler(', 'function(').replace('function function', 'function') %>
<% } %>
<% if(options.debug) { %>
function debug(level, messages) {
if (!(console[level] instanceof Function)) {
@@ -154,19 +158,27 @@ export default (ctx, inject) => {
<% if (options.requestInterceptor) { %>
// Custom request interceptor
const reqInter = <%= serialize(options.requestInterceptor).replace('requestInterceptor(', 'function(').replace('function function', 'function') %>
axios.interceptors.request.use(
(config) => reqInter(config, ctx)
)
const reqInter = <%= serialize(options.requestInterceptor).replace('requestInterceptor(', 'function(').replace('function function', 'function') %>
axios.interceptors.request.use(config => reqInter(config, ctx))
<% } %>
<% if (options.responseInterceptor) { %>

This comment has been minimized.

@wishdevs

wishdevs Aug 31, 2017

I wanted responseInterceptor !!
thanks

// Custom response interceptor
const resInter = <%= serialize(options.responseInterceptor).replace('responseInterceptor(', 'function(').replace('function function', 'function') %>
axios.interceptors.response.use(config => resInter(config, ctx))
<% } %>
// Error handler
axios.interceptors.response.use(undefined, errorHandler.bind(ctx));
// Publish axios to the context
<% if (options.errorHandler) { %>
// Custom error handler
axios.interceptors.response.use(undefined, customErrorHandler.bind(ctx))
<% } %>
// Inject axios to the context as $axios
inject('axios', axios)
// Setup axios helpers
setupHelpers(axios)
}

0 comments on commit b16d6bf

Please sign in to comment.