Should application errors return HTTP 200 OK or one of the typical HTTP error codes?

850 views
Skip to first unread message

jba...@gmail.com

unread,
Apr 26, 2018, 11:48:46 AM4/26/18
to JSON-RPC
The spec doesn't mention HTTP status codes so I think this may be a best practice question. 

For application-type errors (not json parse, param validation errors), should the server return HTTP Status 200 OK or say HTTP 500.

For example, the client calls the server and tries to add a user that already exists. The server responds with error "User already exists".  Should the server respond with a successful HTTP 200 OK response (with the Error object in the response)?

Thanks.

Skylos

unread,
Apr 26, 2018, 12:39:30 PM4/26/18
to json...@googlegroups.com
I'd probably choose 409 Conflict, and put the actual error in the body. - or maybe a 428 precondition required (user does not already exist) - or if system operation allowed for idempotency, provide a put-replaces-existing semantic and have the return status be 200 OK with the body mention that this happened.  But I would not 200 OK the response, unless idempotency is expected.

But that's not json, that's REST, which is a differnet matter entirely than the list on which you sent this message. 

Hm.

David


--
You received this message because you are subscribed to the Google Groups "JSON-RPC" group.
To unsubscribe from this group and stop receiving emails from it, send an email to json-rpc+u...@googlegroups.com.
To post to this group, send email to json...@googlegroups.com.
Visit this group at https://groups.google.com/group/json-rpc.
For more options, visit https://groups.google.com/d/optout.

Felipe Gasper

unread,
Apr 26, 2018, 12:46:16 PM4/26/18
to json...@googlegroups.com
FWIW:

I agree that REST/HTTP questions aren’t (strictly speaking) germane to JSON-RPC; JSON-RPC could just as easily go over WebSocket or SCTP, for example.

That said, IMO it’s worth acknowledging that the lion’s share of JSON-RPC implementations are likely going over REST, so such questions are, IMO, worth discussing as auxiliary implementation considerations.

-Felipe Gasper
Mississauga, Ontario

lnoorde...@gmail.com

unread,
Apr 26, 2018, 3:52:59 PM4/26/18
to JSON-RPC
You have JSON-RPC as a higher level protocol on top of, in this case, HTTP.
So use the HTTP error code to respond at that level (403 not authorized; in case you use Basic Auth).
A 200 message then simply means that there were no errors at the HTTP level.
The JSON-RPC protocol level can still reply with an error message but it was transferred correctly (thats what the 200 is saying).

Or so at least I implemented it for HTTP transfer.
0MQ which I also support does not have such error codes at all.

Skylos

unread,
Apr 26, 2018, 4:36:43 PM4/26/18
to json...@googlegroups.com
You might want to consider that HTTP is subject to application level proxying, caching, and other such matters which are particularly important when considering the semantics of your return codes. Do you WANT it to handle the response exactly as it would a positive response to the endpoint?

Consider the case of a malformed event json-rpc notification event  "POST /jsonrpc HTTP/1.0\n\n{NOTACTUALLYJSON}" - proper REST response here is 400 Bad Request - its actually entirely *impossible* to respond legally in json-rpc to this because its, by definition, a notification, as it has no id.  It also is not a valid json string, but how is the client going to tell whether a valid message was sent, if you had a parse problem with it or not?  Is it always going to return 200 OK even though your bits are falling into the bucket behind the server rack?

This is not exactly a problem with json-rpc - and you can, indeed, choose to return 200 OK just because the application endpoint is a valid one that is running even if the data handed to it is completely bogus.  But if you do this, you're actually doing the transport of the request in a session *that is specifically enveloped and defined with the ability to signal errors in form and process* - and simply ignoring the capability entirely, despite all the benefits of this in non-happy path cases.  You could have as effectively put the data in a udp packet and fired it out your ethernet port like a mortar into a black hole. Zero information received on either end.

As an integrations engineer, this is the kind of brain-dead implementation makes me want to scrape my face off. If there is an error and particularly if it is convenient to do so, signal me so I can at least know something went wrong.

David


--

Alex Efros

unread,
Apr 26, 2018, 6:07:00 PM4/26/18
to JSON-RPC
Hi!

On Thu, Apr 26, 2018 at 08:33:32AM -0700, jba...@gmail.com wrote:
> The spec doesn't mention HTTP status codes so I think this may be a best
> practice question.

It's a question of using right spec:
http://www.simple-is-better.org/json-rpc/transport_http.html

--
WBR, Alex.

jba...@gmail.com

unread,
Apr 26, 2018, 10:21:39 PM4/26/18
to JSON-RPC
Thanks for all the responses. I appreciate it. This question is specifically for JSON-RPC. The last response from Alex points to a page that I have seen before that indicates a HTTP 200 OK for both result and error objects but I'm not sure this is an official source.

Not quite sure I understand Filap's response regarding JSON-RPC over REST? As I understand it REST is a diffn protocol for accessing resources over http and separate from JSON-RPC.

For me, the question boils down to a yes or no. If the application has a known condition that is an error/business rule violation condition for the app should it return HTTP 200 and fill in the error object instead of the result object?

To clarify, say there was a service for inviting people to join a site via email address. If an invite is already sent to that email then another invite should not be sent. The client makes a call to invite an email that has already been invited and the service returns "...has already been invited...".  Should the response be HTTP 200 OK or HTTP 400.x or 500.x?

Alex Efros

unread,
Apr 27, 2018, 5:47:31 AM4/27/18
to JSON-RPC
Hi!

On Thu, Apr 26, 2018 at 07:21:39PM -0700, jba...@gmail.com wrote:
> For me, the question boils down to a yes or no. If the application has a
> known condition that is an error/business rule violation condition for the
> app should it return HTTP 200 and fill in the error object instead of the
> result object?

Yes.

> To clarify, say there was a service for inviting people to join a site via
> email address. If an invite is already sent to that email then another
> invite should not be sent. The client makes a call to invite an email that
> has already been invited and the service returns "...has already been
> invited...". Should the response be HTTP 200 OK or HTTP 400.x or 500.x?

200, if you use HTTP as a transport for JSON-RPC 2.0. Because "transport"
did it work successfully, it delivered both JSON-RPC 2.0 request and
response, so there was no error on transport level.

You don't ask why you don't get a TCP RST packet in same case, don't you?
Because TCP has no errors, it delivers you bytes successfully. What's in
these bytes from your application's point of view - is another story.

--
WBR, Alex.

Артём Хасков

unread,
Aug 19, 2019, 11:13:33 AM8/19/19
to JSON-RPC


четверг, 26 апреля 2018 г., 19:46:16 UTC+3 пользователь Felipe Gasper написал:
FWIW:

Я согласен, что вопросы REST / HTTP (строго говоря) не относятся к JSON-RPC; Например, JSON-RPC может так же легко перейти через WebSocket или SCTP.

Тем не менее, IMO, стоит признать, что львиная доля реализаций JSON-RPC, вероятно, идет по REST, поэтому такие вопросы, IMO, стоит обсудить в качестве вспомогательных соображений реализации.

- Филип Гаспер,
Миссиссауга, Онтарио

> 26 апреля 2018 года, в 12:39, Скайлос < sky ... @ gmail.com > wrote:
>
> Я бы, наверное, выбрал 409 Conflict и поместил бы фактическую ошибку в тело. - или, может быть, требуется предварительное условие 428 (пользователь еще не существует) - или, если системная операция допускает идемпотентность, предоставьте семантику пут-замены-замены и имейте статус возврата 200 ОК с упоминанием тела о том, что это произошло. Но я бы не одобрил ответ, если не ожидается идемпотентность.
>>
Но это не JSON, это REST, который полностью отличается от списка, в который вы отправили это сообщение.
>>
Хм.
>
> David
>
>
> На Чт, 26 апр 2018 в 11:48 < JBA ... @ gmail.com > написал:
> Спецификация Безразлично»
>>
Для ошибок типа приложения (не для анализа json, ошибки проверки параметров), если сервер вернет HTTP Status 200 OK или скажет HTTP 500.
>>
Например, клиент вызывает сервер и пытается добавить уже существующего пользователя. Сервер отвечает с ошибкой «Пользователь уже существует». Должен ли сервер ответить успешным ответом HTTP 200 OK (с объектом Error в ответе)?
>>
Спасибо.
>>
-
> Вы получили это сообщение, потому что вы подписаны на группу JSON-RPC в группах Google.
> Чтобы отписаться от этой группы и прекратить получать от нее электронные письма, отправьте электронное письмо на адрес json ... @ googlegroups.com .
> Чтобы опубликовать в этой группе,json ... @ googlegroups.com .
> Посетите эту группу по адресу https://groups.google.com/ group / json-rpc .
> Дополнительные параметры см. На странице https://groups.google.com/d/ optout .
>>
-
> Вы получили это сообщение, потому что вы подписаны на группу JSON-RPC в группах Google.
> Чтобы отписаться от этой группы и прекратить получать от нее электронные письма, отправьте электронное письмо на адрес json ... @ googlegroups.com .
> Чтобы отправить сообщение в эту группу, отправьте электронное письмо на адрес json ... @ googlegroups.com .
> Посетите эту группу по адресу https://groups.google.com/ group / json-rpc .
> Для получения дополнительной информации посетитеhttps://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages