What is the best way to generate custom errors

Asked

Viewed 104 times

1

For example, the user enters an invalid value, and I want to generate an error. It would be using throw new Error("Você digitou um valor inválido") and dealing with try/catch as in Java? Or there’s a better way to do this with Nodejs?

  • 1

    throw is used for internal errors and "more serious" than a user error. An Alert simply already has the effect of showing that something is wrong. But if you explain better what the user is doing, what is valid and wrong input I can be more specific.

1 answer

1

There is no "best way", but general lines.

A alert() allows sending an error window to the user, but has the problem of blocking the entire browser in the process - may harm the experience of it.
To help your user, you can:

  • Display a tooltip in your input field warning the user that the given value is invalid;
  • Use standard tools to your advantage: when mounting a form within a tag <form>, the browser helps you validate the form. Type fields email, number, or with attributes such as required and maxlength block the <submit> form automatically until all data is in accordance with the requested.
  • Do not leave form validation only on front-end, check the desired types in the back-end and return an error with 500 code (Internal Server Error) for when an invalid input is identified.

For example, to send an error using Express:

app.use(function(err, req, res, next) { 
  console.error(err.stack); 
  res.status(500).send('Something broke!');
});

Other option: You can indicate in the error response which fields are invalid:

 res.status(500).send( JSON.stringify( { invalidFields: ['nome','endereço'] } ));

And in its front-end display a Tarja with the information: "The following fields are in invalid formatting: name, address"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.