Node & Fetch(FE) to set and catch error messages
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
If this tutorial helped you, you can thank me by buying me coffee.