1
\$\begingroup\$

I've set up a simple Node/Express service that creates new bookmarks to a database.

In my Bookmark schema, one of the fields, URL, has validations. When you try to create a new bookmark without the correct validations, it throws an error and a message.

In other words, if you don't provide a URL to the request, then it will throw a message: "Please provide a URL."

The route for the POST request to create a new bookmark:

app.post(
    '/api/bookmarks',
    (req, res) => {
      const { url, tags } = req.body;

      const bookmark = new Bookmark({
        url,
        tags
      });

      bookmark.save()
        .then(res => {
          res.send(result)
        })
        .catch(error => {
          console.log("err:", error);
          res.status(400).send(error)
        });
    }
  );

What my Bookmark schema looks like:

const bookmarkSchema = new Schema({
  url: {
    type: String,
    required: [true, "Please provide a URL."],
    match: [urlRegex, "Your URL is invalid. Please make sure to add www."]
  },
  tags: [String]
});

When I make an API call on the front end client (e.g. via React), I am able to catch the error and subsequent message (Please provide a URL.), but as you can see, I have to call err.response.data.errors.url.message which seems very verbose and long winded.

axios.post('http://localhost:5000/api/bookmarks', { tags: ["banana", "orange"] })
  .then(result => console.log('Result:', result.data))
  .catch(err => console.log('Error:', err.response.data.errors.url.message));

It has me thinking - is there a better way to render errors here? Would it be better handle errors in the client side instead?

I'm quite new to error handling so would like to know what is considered best practice.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.