REST is a stateless architecture in which clients can access and manipulate resources on a server. Generally, REST services utilize HTTP to advertise a set of resources that they manage and provide an API that allows clients to obtain or alter the state of these resources.
In this tutorial, we’ll learn about some of the best practices for handling REST API errors, including useful approaches for providing users with relevant information, examples from large-scale websites and a concrete implementation using an example Spring REST application.
In case code < 200 || code >= 300
(OkHttp handles redirects and so on) RxJavaCallAdapter
will emit onError()
with HttpException
, HttpException
contains response with body and other info.
There are three ways to construct your observable: Observable<BodyType>
, Observable<Response<BodyType>>
, or Observable<Result<BodyType>>
. For the first version, there’s nowhere to hang non-200 resp information so it is included in the exception passed to onError
. For the latter two, the data is encapsulated in the object and can be accessed by calling errorBody()
.
Method Detail
success
public static <T> Response<T> success(@Nullable
T body)
Create a synthetic successful response with body as the deserialized body.
success
public static <T> Response<T> success(int code,
@Nullable
T body)
Create a synthetic successful response with an HTTP status code of code and body as the deserialized body.
success
public static <T> Response<T> success(@Nullable
T body,
okhttp3.Headers headers)
Create a synthetic successful response using headers with body as the deserialized body.
success
public static <T> Response<T> success(@Nullable
T body,
okhttp3.Response rawResponse)
Create a successful response from rawResponse with body as the deserialized body.
error
public static <T> Response<T> error(int code,
okhttp3.ResponseBody body)
Create a synthetic error response with an HTTP status code of code and body as the error body.
error
public static <T> Response<T> error(okhttp3.ResponseBody body,
okhttp3.Response rawResponse)
Create an error response from rawResponse with body as the error body.
raw
public okhttp3.Response raw()
The raw response from the HTTP client.
code
public int code()
HTTP status code.
message
public String message()
HTTP status message or null if unknown.
headers
public okhttp3.Headers headers()
HTTP headers.
isSuccessful
public boolean isSuccessful()
Returns true if code() is in the range [200..300).
body
@Nullable
public T body()
The deserialized response body of a successful response.
errorBody
@Nullable
public okhttp3.ResponseBody errorBody()
The raw response body of an unsuccessful response.
toString
public String toString()
Overrides:
toString in class Object