Hi,
I have a general question about handling errors/ return data eg within an express-api.
It’s related to the projects from: Information Security And Quality Assurance Certification
I’ll try to explain it with some examples from a book-API:
- GET /api/books/5d9c27f93fcfa11b2afb4273
If I provide a valid id and the entry exists I get a JSON-object like
{
"title": "foo",
"_id": "5d9c27f93fcfa11b2afb4273"
}
=> no error
-
GET /api/books/999c27f93fcfa11b2afb4299
The id is valid but there is no result. It is not an error.
What do I return? An empty object?
{}
-
GET /api/books/xxx
The id is not valid. This is an error.
What do I return?
I tried: sending status code 500 in combination with a status text: “id is not valid”
Why? On the frontend jQuery handles errors like this
$.ajax({
url:'/api/books...',
type: 'get',
success: function(data) {...},
error: function(jqXHR, textStatus, errorThrown ) {
// use: jqXHR.responseText;
}
}
So I have a clear way to handle errors.
My question: Is there a common way to structure the return values in APIs?
In the project-examples it is mixed up: sometimes JSON-objects are returned,
sometimes just text (eg: “all books deleted successfully”), sometimes arrays.
I find it difficult/unhandy If you must always check the type of return data.
At least there should be a common way for handling errors for all requests of an API.