Fetch 與 Promise (二):錯誤處理


Posted by s103071049 on 2021-07-10

所謂的錯誤並不是 Http response status 拿到 400, 500,因為我的 request 成功地發出也確實地收到 response。

錯誤指的是我連 response 都拿不到的那種。ex: uncaught typeError: fail to fetch

同步的程式碼,可以利用 try catch 處理錯誤。(非同步基本上不能使用 try catch)

非同步、 GET 錯誤處理 .catch( )

非同步的程式碼,舉例:網路有關的、call back function,利用 .catch() 處理錯誤,.catch()

const api200 = 'zzzhttps://run.mocky.io/v3/82ec874a-086c-48ef-8195-37686b61f372'
fetch(api200)
  .then((response) => {
    return response.text()
  }).then(text => {
    console.log(text)
  }).catch(err => {
    console.log('err', err)
  })

非同步、 POST 錯誤處理 .catch( )

fetch(網址, {物件}, headers)

物件裡可以傳幾個東西:

  1. method
  2. body (request 的 raw body,所以如果要傳 json 格式的資料,就要放 JSON.stringify())
  3. headers,根據 content type 的不同,會有不同放 body 的方式。
const data = {
  name : 'apple'
}
fetch(api200, {
  method : 'POST',
  body: JSON.stringify(data),
  headers: new Headers({
    'Content-Type': 'application/json'
  })
})
  .then((response) => {
    return response.text()
  }).then(text => {
    console.log(text)
  }).catch(err => {
    console.log('err', err)
  })

#get #post #error #fetch







Related Posts

Some relative page about the "dependent types"

Some relative page about the "dependent types"

加密和雜湊有什麼不同?

加密和雜湊有什麼不同?

npm、yarn 用法簡介

npm、yarn 用法簡介


Comments