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

Sylar
  • 11,422
  • 25
  • 93
  • 166
  • Possible duplicate of [How can I get the status code from an http error in Axios?](https://stackoverflow.com/questions/39153080/how-can-i-get-the-status-code-from-an-http-error-in-axios) – Sylar Jun 09 '17 at 16:19

3 Answers3

20

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);
    });
Matija Župančić
  • 1,080
  • 2
  • 11
  • 21
1

This may help

catch (error) {
            if (error.response) {
                console.log(error.response)
                console.log(error.response?.data?.message)
                return 
            }
        }
-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

Ray Jumi
  • 1
  • 1
  • can you elaborate why removing the responseType can solve this problem? – Lex May 23 '18 at 02:51
  • 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 type – Ray Jumi May 23 '18 at 06:06