VueなりReactなりでAPIに投げる時fetchAPIなりaxiosを使うことが多いかと思います。
エラー処理とかを共通化したいなってとき
import axios from 'axios'
import { InValidServiceException, UnAuthorizedException, ConfirmServiceException, TokenMismatchException, InternalServerException, UnprocessableException } from './config/exception' // eslint-disable-line no-unused-vars
import { useUserStore } from '@/stores/user'
export const API = axios.create({
withCredentials: true,
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
})
export const MULTIPART = axios.create({
withCredentials: true,
headers: {
'Content-Type': 'multipart/form-data'
}
})
API.interceptors.request.use(config => {
const token = useUserStore().token;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, error => {
return Promise.reject(error);
});
API.interceptors.response.use((response) => response, async (error) => {
if (error.response) {
if (error.response.status === 401) {
const { message, data } = error.response.data
throw new UnAuthorizedException(data, message)
}
if (error.response.status === 409) {
const { message } = error.response.data
throw new ConfirmServiceException(message)
}
if (error.response.status === 400) {
const { message, data } = error.response.data
throw new InValidServiceException(data, message)
}
if (error.response.status === 419) {
throw new TokenMismatchException()
}
if (error.response.status === 500) {
let { message, data } = error.response.data
throw new InternalServerException(data, message)
}
if (error.response.status === 422) {
const { message, data } = error.response.data
throw new UnprocessableException(data, message)
}
}
throw new Error('unknown')
})
こんな感じで返ってきた時にインターセプトして処理を書く
コメント