How to make a query that returns 404 if an entry not found.

Hello everyone! I am currently using the below query to retrieve a single entry of the restaurants table using the slug:
supabase
.from('restaurants')
.select(
`
id,
name,
slug,
logo`
)
.eq("slug", slug)
.single();
supabase
.from('restaurants')
.select(
`
id,
name,
slug,
logo`
)
.eq("slug", slug)
.single();
However, I am getting this error when it doesn't find an entry (what I think is kind of expected) but I would like to get a 404 like error so it is explicit about the failure and a "Not Found" UI can be rendered. If that is not possible which should be the suggested pattern to follow in this case.
406 Not Acceptable
{
"code": "PGRST116",
"details": "The result contains 0 rows",
"hint": null,
"message": "JSON object requested, multiple (or no) rows returned"
}
406 Not Acceptable
{
"code": "PGRST116",
"details": "The result contains 0 rows",
"hint": null,
"message": "JSON object requested, multiple (or no) rows returned"
}
4 Replies
garyaustin
garyaustin2y ago
You can't change the response codes. Normally not found in Postgres is an empty result and there is no error.
.single() adds a check on the data being a single row and errors if it is not. If you do not have .single() you will get empty array and have to know that is no data. What you don't know if it is because the row does not really exist or if RLS hid it.
Snorku
SnorkuOP2y ago
Well restaurants table can be read even by anon users so I think if the query returns and empty array I can safety say it is because the entry does not exists (aka 404)
garyaustin
garyaustin2y ago
OK.
Snorku
SnorkuOP2y ago
Thanks a lot for your help!

Did you find this page helpful?