How to display response error message with axios
Asked Answered
P

3

9

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

Plasmagel answered 6/6, 2017 at 9:9 Comment(1)
Possible duplicate of How can I get the status code from an http error in Axios?Plasmagel
K
21

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);
    });
Kendra answered 6/6, 2017 at 9:29 Comment(5)
Nothing returns the message I set: Foo bar!Plasmagel
Did you try with e.message?Tolle
I got Request failed with status code 406. Im using Laravel if that makes a different. But Chrome dev tools show the actual message Foo bar!Plasmagel
Let us continue this discussion in chat.Tolle
Line 4 Missing '{'Selfjustifying
F
1

This may help

catch (error) {
            if (error.response) {
                console.log(error.response)
                console.log(error.response?.data?.message)
                return 
            }
        }
Foliate answered 20/6, 2022 at 20:24 Comment(0)
I
-1

I have encountered this problem. i created an axios instance, the responseType is 'json', axios.create({ ... responseType: 'json' })

response type is not json,so i can't got it. remove this property can solve this problem

Innes answered 23/5, 2018 at 2:17 Comment(2)
can you elaborate why removing the responseType can solve this problem?Echinoderm
The response content-type returned by the server is not json, is 'arraybuffer', 'blob', 'document', or other ,i set json,so can not get other typeInnes

© 2022 - 2024 — McMap. All rights reserved.