1
0
mirror of https://github.com/twirl/The-API-Book.git synced 2025-08-10 21:51:42 +02:00

Clarifications regarding RFC 9457

This commit is contained in:
Sergey Konstantinov
2023-08-10 15:07:05 +03:00
parent e3ca790b8f
commit abd2f42dd9
2 changed files with 10 additions and 0 deletions

View File

@@ -61,6 +61,11 @@ Even if we choose this approach, there are very few status codes that can reflec
The editors of the specification are very well aware of this problem as they state that “the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition.” This, however, contradicts the entire idea of a uniform machine-readable interface (and so does the idea of using arbitrary status codes). (Let us additionally emphasize that this lack of standard tools to describe business logic-bound errors is one of the reasons we consider the REST architectural style as described by Fielding in his 2008 article non-viable. The client *must* possess prior knowledge of error formats and how to work with them. Otherwise, it could restore its state after an error only by restarting the application.)
NB: Not long ago, the editors of the standard proposed their own version of the JSON description specification for HTTP errors — [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html). You can use it, but keep in mind that it covers only the most basic scenario:
* The error subtype is not transmitted in the metadata.
* There is no distinction between a message for the user and a message for the developer.
* The specific machine-readable format for error descriptions is left to the discretion of the developer.
Additionally, there is a third dimension to this problem in the form of webserver software for monitoring system health that often relies on status codes to plot charts and emit notifications. However, two errors represented with the same status code — let's say, wrong password and expired token — might be very different. The increased rate of the former might indicate brute-forcing of accounts, while an unusually high frequency of the latter could be a result of a client error if a new version of an application wrongly caches authorization tokens.
All these observations naturally lead us to the following conclusion: if we want to use errors for diagnostics and (possibly) helping clients to recover, we need to include machine-readable metadata about the error subtype and, possibly, additional properties to the error body with a detailed description of the error. For example, as we proposed in the “[Describing Final Interfaces](#api-design-describing-interfaces)” chapter:

View File

@@ -59,6 +59,11 @@ If-Match: <ревизия>
Разработчики стандарта HTTP об этой проблеме вполне осведомлены, и отдельно отмечают, что для решения бизнес-сценариев необходимо передавать в метаданных либо теле ответа дополнительные данные для описания возникшей ситуации («the server SHOULD send a representation containing an explanation of the error situation, and whether it is a temporary or permanent condition»), что (как и введение новых специальных кодов ошибок) противоречит самой идее унифицированного машиночитаемого формата ошибок. (Отметим, что отсутствие стандартов описания ошибок в бизнес-логике — одна из основных причин, по которым мы считаем разработку REST API как его описал Филдинг в манифесте 2008 года невозможной; клиент *должен* обладать априорным знанием о том, как работать с метаинформацией об ошибке, иначе он сможет восстанавливать своё состояние после ошибки только перезагрузкой.)
**NB**: не так давно разработчики стандарта предложили собственную версию спецификации JSON-описания HTTP-ошибок — [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html). Вы можете воспользоваться ей, но имейте в виду, что она покрывает только самый базовый сценарий:
* подтип ошибки не передаётся в мета-информации;
* нет разделения на сообщение для пользователя и сообщение для разработчика;
* конкретный машиночитаемый формат описания ошибок остаётся на усмотрение разработчика.
Дополнительно, у проблемы есть и третье измерение в виде серверного ПО мониторинга состояния системы, которое часто полагается на статус-коды ответов при построении графиков и уведомлений. Между тем, ошибки, скрывающиеся под одним статус кодом — например ввод неправильного пароля и истёкший срок жизни токена — могут быть очень разными по смыслу; повышенный фон первой ошибки может говорить о потенциальной попытке взлома путём перебора паролей, а второй — о потенциальных ошибках в новой версии приложения, которая может неверно кэшировать токены авторизации.
Всё это естественным образом подводит нас к следующему выводу: если мы хотим использовать ошибки для диагностики и (возможно) восстановления состояния клиента, нам необходимо добавить машиночитаемую метаинформацию о подвиде ошибки и, возможно, тело ошибки с указанием подробной информации о проблемах — например, как мы предлагали в главе «[Описание конечных интерфейсов](#api-design-describing-interfaces)»: