Sylar
Sylar

Reputation: 12072

How to display response error message with axios

Been looking to achieve this few months now but now it's needed. I need to display the error message, set on server, about what went wrong:

Sever endpoint

abort(406, 'Foo bar!')

Web:

[...]
 .catch(e => {
  console.log(e.response.data) // does not work
 })

In chrome dev tools, under preview, I see the message Foo bar!. How to get this message on my console log?

This endpoint will have different abort messages based on actions so I do not want to set a static error message on web for the error.

Chrome dev tools message: enter image description here

Upvotes: 9

Views: 29310

Answers (2)

Ayooluwa Aduwo
Ayooluwa Aduwo

Reputation: 49

This may help

catch (error) {
            if (error.response) {
                console.log(error.response)
                console.log(error.response?.data?.message)
                return 
            }
        }

Upvotes: 1

Matija Župančić
Matija Župančić

Reputation: 1140

This should work : console.log(e.response.data.message). I think this is what you looking for.

This is for this type of request:

axios.post(
    url,
    {},
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error.response.data.message);
    });

Upvotes: 21

Related Questions