meilisearch-java icon indicating copy to clipboard operation
meilisearch-java copied to clipboard

Throw a specific Exception instead of `Exception` in handlers

Open alallema opened this issue 3 years ago • 0 comments

Following this discussion, it could be better to throw specifics Exceptions for all the handlers:

I mean, is good to only throw errors that we can control, Exception is Ok, but in the end is easier for the consumer just to expect a MeiliSearchApiException instead of the Exception because they will have more control over the exception catch flow like this:

// when we just throw a Meilisearch error, the user can catch all the Meilisearch errors first:
// of course, they need to respect an inheritance (we can talk about this later).

try {
  client.index("movies").anyMethodThatThrowsSomething();
} catch(MeiliSearchOtherException e) {
  // do something with a meilisearch error.
} catch(MeiliSearchActionException e) {
  // do something with a meilisearch error.
} catch(MeiliSearchApiException e) {
  // do something with a meilisearch error.
}

Now if we just throw an Exception:

// in this new case, we can see the code is different and harder to read because they had to handle "multiple" 
// different exception possibilities or even check if this exception isn't coming from the okhttp for example.

try {
  client.index("movies").anyMethodThatThrowsSomething();
} catch(Exception e) {
   if (e.message.startsWith("message")) // do something
   else if (e.message.startsWith("other message")) // do other thing 
}

Originally posted by @brunoocasali in https://github.com/meilisearch/meilisearch-java/pull/371#discussion_r873405055

alallema avatar May 18 '22 09:05 alallema