Search code examples
javascriptexceptionaxioshttp-status-codesstatus-message

Can't access res.statusMessage in Javascript async/await try/catch client code to read exception thrown from express backend


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.


Solution

  • 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);
      }
    }