HTTP response body preservation on error¶
HTTP response body preservation on error is a design pattern in API development where the client application retains and processes the body of an HTTP response even when the response indicates a failed status code (e.g., 4xx or 5xx).^[400-devops__09-Scripting-Language__31-kotlin__kotlin.md]
Rationale¶
In many API designs, errors are not signaled solely by the status code. Servers often return a rich JSON or XML object in the response body containing detailed diagnostic information, such as specific error codes, human-readable messages, or validation failure details^[400-devops__09-Scripting-Language__31-kotlin__kotlin.md]. Discarding the body on error prevents the client from accessing this context, making it difficult to handle the error gracefully or inform the user.
Implementation¶
Implementing this pattern typically involves ensuring that the HTTP client logic does not treat non-2xx status codes as an exception that automatically discards the payload^[400-devops__09-Scripting-Language__31-kotlin__kotlin.md].
In the context of [[kotlin]] development using frameworks like Ktor, this is achieved by handling the response object manually. For example, rather than letting a standard HTTP client throw an exception for a 401 Unauthorized error, the developer can inspect the response object, read the content (body), and then decide whether to throw an application-specific exception or handle the failure logic^[400-devops__09-Scripting-Language__31-kotlin__kotlin.md].
Related Concepts¶
- [[kotlin]]
- HTTP Status Codes
- [[Exception Handling]]
Sources¶
^[400-devops__09-Scripting-Language__31-kotlin__kotlin.md]