Info
- BE API ํต์ ์, responseCode์ ๋ฐ๋ผ ๋ถ๋ฅ๋๋ ์๋ฌ ์ผ์ด์ค.
- ์๋ฌ ์ผ์ด์ค์ ๋ฐ๋ผ ํ๋ฉด์์ ์ฒ๋ฆฌํ๊ธฐ ์ฝ๋๋ก enumํ ํ์ฌ ์ฌ์ฉ.
- ํ์ฌ API์์ ๋ฐ์ํ ์๋ฌ๋ฅผ ํ๋ฉด๊น์ง ํจ์จ์ ์ผ๋ก ๊ฐ์ ธ์ฌ ์ ์๋ ๋ฐฉ๋ฒ์ด ๋ง๋ ํ์ง ์์ ๊ณ ๋ฏผ์ค.
Structure
- Error ๋ฐ์ ์, responseCode์ ๊ธฐ์กด Error ๊ฐ์ฒด๋ฅผ ์ฌ์ฉํ์ฌ ApiError ์์ฑ
import { ApiCode } from '@utils/error/constant/ApiCode'
class ApiError extends Error {
public apiCode: ApiCode
public originalError?: Error
constructor(code: ApiCode, originalError?: Error) {
super(code)
this.name = `${this.constructor.name}.${code}`
this.apiCode = code
this.originalError = originalError
}
toString() {
return `code: ${this.apiCode}\noriginalError: ${this.originalError?.name}\n${this.originalError?.message}`
}
}
export default ApiErrorUsage
- repository์์ API ํต์ ์ ํตํด ๊ฐ์ ๊ฐ์ ธ์ฌ ๊ฒฝ์ฐ, ์คํจ ์ฌ๋ถ๋ฅผ ํ๋จํ์ฌ ApiError๋ฅผ throw
login: async (username: string, password: string) => {
const apiResponse: ApiResponse<Token> = new ApiResponse<Token>().parseData(
await api().post('login', {
username: username,
password: password
})
)
if (apiResponse.isFailure) throw new ApiError(apiResponse.code)
tokenRepository.setToken(apiResponse.body!)
return apiResponse.body!
}- ํด๋น function์ ์ฌ์ฉํ๋ ViewModel์์ try/catch๋ฅผ ํตํด ApiError๋ฅผ catch โ ์๋ฌ์ ๋ํ ๋์
- ์ด๋, catch์ ์ธ์์ธ e์ ํ์ ์ ์ ์ถํ ์ ์๊ธฐ ๋๋ฌธ์ ํ์ ์ ์ ํ๋ ๋ก์ง์ด ๋งค์ฐ ๊ธธ์ด์ง.
- ํด๋น function ์์ฒด๋ try/catch๋ฅผ ํตํด Error๋ฅผ ๊ฐ์งํ๊ธฐ ๋๋ฌธ์ ๋ก์ง ์์ฒด๊ฐ ์๋ฏธ๋ณด๋ค ๊ธธ๊ฒ ๋์ด์ง ํํ๊ฐ ๋๋ค.
const login = async () => {
if (!validate()) return
setLoading(true)
try {
const token: Token = await authRepository.login(username.value, password.value)
if (token.accessToken && token.refreshToken) {
setAuthorization({ isAuthorized: true, userInfo: await authRepository.getUserInfo() })
navigate('/', { replace: true })
}
} catch (e) {
handleLoginError(e)
} finally {
setLoading(false)
}
}