0
1

axios(ajax)でエラー時のレスポンスbodyが取得できなかったので調べてみた

Posted at

はじめに

RailsのAPIからデータを取得する際に、axiosを使用してエラーが発生した場合、レスポンスを取得することができずに困った

問題点

Railsでエラーが発生した場合、通常はstatusコードとmessageをレスポンスボディとして返すので取得の仕方を変えないといけなかった

例えば

if user.save
  render json: { status: 200, data: user }
else
  render  status: :unprocessable_entity, json:{ messages: user.errors.full_messages }
end

この場合、フロントでaxiosを使用してAPIを呼び出すと、エラーが発生した場合、以下のようなエラーが発生する

axios
  .post(process.env.API_URL + '/api/v1/users/signup')
  .then((res) => {
    console.log(res)
  })
  .catch((e) => {
    console.log(e)
  })

出力

Error: Request failed with status code 422
    at createError (createError.js?2d83:16)
    at settle (settle.js?467f:17)
    at XMLHttpRequest.handleLoad (xhr.js?b50d:69)

このエラーは、axiosがエラーが発生した場合、レスポンスbodyをe.responseオブジェクトとして返す
e.responseオブジェクトは、エラーが発生した場合、statusコードとmessageのみを返し、messagesなどの詳細なエラー情報を取得することができない

対処法

この問題を解決するには、フロントでaxiosのcatch()メソッドの引数にresponseオブジェクトを渡して、response.dataオブジェクトからエラー情報を取得

axios
  .post(process.env.API_URL + '/api/v1/users/signup')
  .then((res) => {
    console.log(res)
  })
  .catch((e) => {
    console.log(e.response.data.messages)
  })

出力

["Email has already been taken.", "Password is too short."]

この方法で、エラーが発生した場合でも、詳細なエラー情報を取得することができる

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1