Skip to content

Incorrect 404 error handling for mongoose findOne #3024

Closed
@lindapaiste

Description

@lindapaiste

Increasing Access

We want our APIs to return accurate and descriptive errors, even when provided with invalid arguments.

Feature enhancement details

Problem

When our project API is called with an invalid project id it will return a 200 success error code with the body null instead of the appropriate 404 not found error code.

To Reproduce

You can open the dev tools console on https://editor.p5js.org/ and paste the following snippet. You must be in a window with the editor due to cross-origin policies.

fetch("https://editor.p5js.org/editor/lindapaiste2/projects/wrong")
  .then(res => res.json().then(json => console.log('status', res.status, 'json', json)))

I'm not flagging this is a "bug" since it has no repercussions on the editor web app. You can't make this API call by navigating to an incorrect URL, since we will not load the page for a project which doesn't exist. The bug is only seen when querying the API directly.

Root Cause

The problem is in the following code in the project.controller:

Project.findOne({
user: user._id,
$or: [{ _id: projectId }, { slug: projectId }]
})
.populate('user', 'username')
.exec((err, project) => { // eslint-disable-line
if (err) {
console.log(err);
return res
.status(404)
.send({ message: 'Project with that id does not exist' });
}
return res.json(project);
});

The mongoose findOne function with not return an err when there is no document. This is considered normal behavior and not an error. It will return a null project, so we need to check for that. In other places we handle this with if (err || !project) {.

err here would be some unforeseen problem in mongoose, and should probably be a 500 internal server error instead of a 404 not found, in my opinion. I think we can let the error be thrown and caught by default express error-handling middleware?

Tasks:

  • Fix the above code to return a 404 when there is no project found.
  • Find other places in the code where we make this type of error
  • Create tests for the project.controller file to verify the current incorrect behavior and future correct behavior. We want to know that an API request with a valid username but an invalid projectId would return a 404 not found error.

Metadata

Metadata

Assignees

Labels

Area: TestingFor tests, test coverage, or testing infrastructureArea:BackendFor server-side logic, APIs, or database functionality

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions