0

enter image description here

Chrome can read the message provided by the server (No project found for 70100) but when I console.log(err.message) I just get Request failed with status code 400

Client code:

const doFetch = async () => {
      try {
          const {data} = await axios.post('/docs/query/project', {projectId: '70100'});
          console.log(data);
          setFetched(data);

      } catch (err) {
        console.log(err.message);
      }
    }

Server code:

try {
        const docs = await docsDb.getProject(projectId);
        res.json(docs);
    } catch(err) {
        res.statusMessage = `No project found for ${projectId}`;
        res.status(400).end();
    }

It's annoying that Chrome can read my message, but I can't figure out how to display it to the user. Obviously the message is getting as far as the browser, I would appreciate some tips on how to access it in my client code! Thanks in advance.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
shaz
  • 2,317
  • 4
  • 27
  • 37
  • 4
    Inspect the ‘err’- object, it likely has ‘err.response’ set. More info: https://github.com/axios/axios/blob/master/README.md#handling-errors – Geert-Jan Nov 11 '19 at 23:39

2 Answers2

1

err.response.statusText on the client contains the text set in res.statusMessage on the server.

Live and learn

shaz
  • 2,317
  • 4
  • 27
  • 37
1

The statusMessage sent in the node response surfaces in the Axios response as a statusText property. You can see the response object associated with a failed request by looking at the err.response property of an Axios error. Be careful, though; if no HTTP request was issued because the error relates to things like connection failures, err.response won't exist.

const doFetch = async () => {
  try {
    const {data} = await axios.post('/docs/query/project', {projectId: '70100'});
    setFetched(data);
  } catch (err) {
    const message = err.response
      ? `Request failed with ${err.response.status}: ${err.response.statusText}`
      : err.message;
    console.error(message);
  }
}
Jacob
  • 77,566
  • 24
  • 149
  • 228