Node & Fetch(FE) to set and catch error messages
While working on a client front-end and a back-end API, I bumped on the need to create a custom error message with Node in the API, catch the message with fetch, and display that message on the client side with JavaScript. Before sharing my solution, a reminder that user input should be checked on the client side before sending it to the API. Since we can’t foresee all possible error cases, it is a good idea to check the input also on the server side, respond with a meaningful error message, and display the message to the user on the client side.
This is a simplified version of the Express API router code, where I handle the post request to create a new user:
The part I was getting wrong at the beginning, is that instead of setting the error message in response.statusMessage
, I was setting it in the body of the response, like response.stateus(400).end('Error message here')
. Because of that, I was not able read it when catching the error on the client side.
This is the service on the client side, that sends the request to the back-end API:
As you can see, I am not catching the error yet, but throwing a new error with the response.statusText
, corrensponding to the statusMessage
in Node, if the response status code is not within 200–299.
This is the handle that is triggered when the user submits the form. It also catches the error and sets the notification messages which are shown to the user:
The form, which is not displayed in here, has the mandatory fields set as required and input checks. Also, for a matter of brevity, I leave out the logic behind the props.setNotification
function.
If this tutorial helped you, you can thank me by buying me coffee.