Вопрос

Trying to tidy up my code, but ran into an issue on a neat way to allow for pieces of business logic to report errors (at potentially multiple errors) to the user interface.

e.g. for the "simple" act of registering a user, I might have a non-ui method that looks like

public User register(String name, String email, String password);

Which has quite a long list of potential errors, e.g.

  • Invalid username / email / password. In theory this is checked by the UI, but the server also checks for security. Shouldn't really happen.
  • Failed to make a HTTP call to the server (IOException from Apache HTTPClient).
  • Non 200 OK server HTTP response or failed to parse the servers JSON response
  • Username already used
  • Email already used (might happen at the time time as username already used)

For the first 3 I was thinking of throwing some kind of exception the user interface understands, and can display in a dialogue box, e.g.

throw LocalisedException(Strings.serverCommunicationFailed);

But for the last 2 I am really not sure. My old code just checked the relevant part of the JSON directly and then updated a text label next to the user input fields directly. But now I am trying to separate things they can't see each other to do that anymore and creating an exception object for this doesn't feel very exceptional (especially in similar error cases, e.g. say on a shop a custom wants to add 50 of x to the basket, but the server says there is only 45).

I am sure there is a standard pattern for this, but seems I have been looking in the wrong places (e.g. http://www.google.com/search?q=Google+user+interface+error+reporting )

Нет правильного решения

Другие советы

You could define a custom InvalidFieldException for:

  • Invalid username / email / password
  • Username already used
  • Email already used

which contains a Map describing all the errors where the key is the field identifier, and the value the associated error message.

For:

  • Failed to make a HTTP call to the server (IOException from Apache HTTPClient)
  • Non 200 OK server HTTP response or failed to parse the servers JSON response

You can just define one or two dedicated exceptions and print a message on the screen for the user.

It is also a bad practice to put validation only in your ui, it should at least append in your model.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top