Description
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
:
p5.js-web-editor/server/controllers/project.controller.js
Lines 94 to 107 in 6cac275
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.