apisauce
apisauce copied to clipboard
addMonitor run after addResponseTransform ?
I have addResponseTransform for transform data form respond and handle error message then throw to catch later
api.addResponseTransform((response) => {
if (response.status >= 400 || !response.ok) {
const error = new Error(
response.data?.message || response.originalError.message || response.problem,
)
error.status = response.status
error.response = response
// throw error
}
if (response.ok && response.data.code === 0) {
// just mutate the data to what you want.
response.data = response.data.data
} else {
const error = new Error(response.data?.message)
error.status = response.data?.code
error.response = response
throw error
}
if (response.ok) {
if (response.data.code === 0) response.data = response.data.data
else {
response.ok = false
response.problem = response.data?.message
response.status = response.data?.code
}
}
})
And I have addMonitor for handle status like 401 for auto-logout
const naviMonitor = (response) => {
if (response.status === 401) {
console.warn('Unhandled session expiration')
signOut()
}
}
api.addMonitor(naviMonitor)
but don't work when addResponseTransform have throw error function
what do you suggest me? I have a way to fix it that I move throw error into each of functions which use API
ie.
api.addResponseTransform((response) => {
if (response.ok) {
if (response.data.code === 0) response.data = response.data.data
else {
response.ok = false
response.problem = response.data?.message
response.status = response.data?.code
}
}
})
export const approve = (payload = {}) => {
return api
.post(`/approve`,payload)
.then((response) => {
if (!response.ok) {
const error = new Error(response.data?.message)
error.status = response.data?.code
error.response = response
throw error
}
})
}
If you throw an error it will go to the catch
const naviMonitor = (response) => {
try{
if (response.status === 401) {
console.warn('Unhandled session expiration')
signOut()
}
} catch(e) {
console.log(e) // the error you throwed at transformation
}
}
api.addMonitor(naviMonitor)