OpenCageData / jopencage

OpenCage geocoding client for Java
Apache License 2.0
4 stars 0 forks source link

[jOpenCage] Introduce dedicated exceptions for various potential errors #32

Open tsamaya opened 10 months ago

tsamaya commented 10 months ago

The package logs the error and returns null. Structuring the exceptions to distinguish between client-side and server-side errors from OpenCage API would help to react to HTTP errors.

code meaning
200 OK (zero or more results will be returned)
400 Invalid request (bad request; a required parameter is missing; invalid coordinates; invalid version; invalid format)
401 Unable to authenticate - missing, invalid, or unknown API key
402 Valid request but quota exceeded (payment required)
403 Forbidden (API key disabled or IP address rejected)
404 Invalid API endpoint
405 Method not allowed (non-GET request)
408 Timeout; you can try again
410 Request too long
426 Upgrade required (unsupported TLS)
429 Too many requests (too quickly, rate limiting)
503 Internal server error

Error code can be found at https://opencagedata.com/api#codes

tsamaya commented 10 months ago

An Idea from https://stackoverflow.com/a/47058425/1910637

Quick answer

In Spring you have exactly what you want:

HttpClientErrorException - Exception thrown when an HTTP 4xx is received. HttpServerErrorException - Exception thrown when an HTTP 5xx is received.

And a recommended practice

Minimally, you should differentiate exceptions related to business logic (e.g., insufficient balance, email address is not valid) from other exceptions (e.g., server not available, unsupported media type, SQLException).

In our REST API, we have a library for Java clients that parses responses and throws only three different exceptions:

400, 401, 403, 404, 409, 422: throw MyBusinessException, which contains a message that can be shown to the end user. The message comes in the response body (exception handling on the service side), but if not present we have a default message specific to each status code. 405, 412, 415: throw HttpClientErrorException with a message that is specific to each status code. other 4xx codes: throw HttpClientErrorException with a generic message. 5xx codes: throw HttpServerErrorException with a generic message. All these exceptions are unchecked.

tsamaya commented 10 months ago

Each HTTP Error code would have its own Exception, they all extend a base exception.

tsamaya commented 10 months ago

Following a discussion with @lpellegr, the exception names won't always reflect the transport used.

The base exception is going to be JOpenCageException.

PR #33 is merged into the release-3.0.0 branch and a snapshot version is available for testing on https://oss.sonatype.org/content/repositories/snapshots/com/opencagedata/jopencage/3.0.0-SNAPSHOT/

NB: Keeping this issue open up to the v3 release