Handling Mongoose validation errors – where and how?

后端 未结 9 1743
孤城傲影
孤城傲影 2020-12-23 19:45

I\'m trying to decide how I want to handle validation errors in Mongoose.

Custom error messages using node-validator

I have defined my own validation rules

9条回答
  •  余生分开走
    2020-12-23 20:07

    The question you need to ask yourself is who is responsible for causing the error in the first place?

    If this happens in your system, that you are in control over, just let the errors hit you like you normally would, and weed the bugs out as you go along, but I suspect you are doing an application which is facing real world users and you want to sanitize their inputs.

    I would recommend that client side you check that the input is correct before you send it to your server, and you show nice helper messages like "Your username must be between x and y characters".

    Then on the server side you expect that in 99% of the cases the input will come directly from your sanitizing client, and so you still validate it using the techniques you already suggested, but if there is an error you simply return a general error message to the user interface - since you trust that your user interface would have shown helper messages so the validation error must be caused by a bug or a hacking attempt.

    Remember to log all server side validation errors as they could be severe bugs or someone looking for exploits.

提交回复
热议问题