Handle cast error on find when objectId is invalid
Problem
Do you want to request a feature or report a bug? Bug What is the current behavior? I'm trying to find an item by its _id, but when I try to handle the possible "error", when the client sends an id that doesn't exist and then return it as an user friendly error, it's getting into the "catch" function and resulting in an Error 500 to the user with a very big error message. I tried to find a method to handle it on google and even here, but I didn't find anything. If the current behavior is a bug, please provide the steps to reproduce. [code block] What is the expected behavior? I want to handle this kind of "error" that for me isn't an error. It's just an invalid item to search. Please mention your node.js, mongoose and MongoDB version.* Node: v7.4.0 Mongoose: 4.10.5 MongoDB: v3.4.4
Error Output
Error 500 to the user with a very big error message.
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Solution: Handle cast error on find when objectId is invalid
This is expected behavior and your way of handling the error is mostly correct. I'd recommend instead doing: [code block] Checking for `instanceof CastError` is more robust because the error message may change. If you don't want to execute this check for every `find` operation you can use error handling middleware to transform the error into something that is appropriate for your application.
Trust Score
4 verifications
- 1
This is expected behavior and your way of handling the error is mostly correct.
This is expected behavior and your way of handling the error is mostly correct. I'd recommend instead doing:
- 2
Checking for `instanceof CastError` is more robust because the error message may
Checking for `instanceof CastError` is more robust because the error message may change.
- 3
If you don't want to execute this check for every `find` operation you can use e
If you don't want to execute this check for every `find` operation you can use error handling middleware to transform the error into something that is appropriate for your application.
Validation
Resolved in Automattic/mongoose GitHub issue #5354. Community reactions: 6 upvotes.
Verification Summary
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep