How to write proper error message for the users?

Viewed 61

Okay so this is what I find quite difficult most of the time. That is, to write proper error messages for the client to see when there is an error.

An example of a situation would be where I am using Axios and a third party api to get data. I need to write proper error messasges for both Axios' errors as well as errors from the api.

According to Axios' error handling documentation:

try {
  
} catch ( err ) {

      if ( err.response ) {

            // client received an error response (5xx, 4xx)

      } else if ( err.request ) {

            // client never received a response, or request never left

      } else {

            // anything else

      }

}

And the third-party api's error is an object inside err.response called data. So therefore, my catch block looks like this:

try {
  
} catch ( err ) {

      if ( err.response ) {

             if ( err.response.data ) {

                // api error
                return;

             }

            // client received an error response (5xx, 4xx)

      } else if ( err.request ) {

            // client never received a response, or request never left

      } else {

            // anything else

      }

}

For the API errors, I could simply use err.response.data.message as the messages are straight-forward and simple to understand for the users. But the problem is for the other type of errors that could arise from Axios or from my server. And Axios doesn't provide simple messages.

So what could I respond with in these situations? I could just respond with Something went wrong, please try again but that would be too vague.

Someone please help.

1 Answers

Here's what I have done. It involves two things

  1. attaching some sort of unique identifier to the message bounced back to the user.
  2. using console.error() or some similar logging operation to log the message internally so you can troubleshoot it.
   if ( err.response ) {
        /* format and send the useful err.response message to the browser user */
        return
      } else {
        const errid = uuidv4()
        const message = 'Something went wrong. ' +
          'If it keeps happening please contact us and mention error id ' + 
          errid
        console.error (message, err)
        /* send the message to the browser user */ 
        return
      }

This gives your unlucky user confidence that you can troubleshoot the problem. It also gives you enough data to troubleshoot it.

Once you get some real-world experience with the API that might cause trouble, you can improve the error processing, and even consider retrying the requests. But until you have experience you can't do that.

Related