Java user interface error reporting - java

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.

Related

validate REST endpoint design

REST endpoint design says: Not use verb
In an workflow-like create Employee which has multi-tab style like "Basic Details", "Educational Details", "Work Experience", etc... One first tab data is filled continue button is pushed resulting in an backend API call which just validates the detail in that tab and returns the list of validation errors if any or moves to next tab for the user to fill data. So basically this calls for validate API for each of the tabs with no intention of saving data. Now one thing that comes naturally is below:
POST /employee/basic/validate
(removing api versioning details from endpoint for simplicity)
But using validate in API means verb. How to design then?
There's a separate flow where one can just save "basic details" of employee - so its like any normal API validate and save - so POST /employee/basic/ is good for that case.
REST endpoint design says: Not use verb
That's not a REST constraint - REST doesn't care what spellings you use for your resource identifiers.
All of these URL work, exactly the way that your browser expects them to:
https://www.merriam-webster.com/dictionary/post
https://www.merriam-webster.com/dictionary/get
https://www.merriam-webster.com/dictionary/put
https://www.merriam-webster.com/dictionary/patch
https://www.merriam-webster.com/dictionary/delete
Resources are generalizations of documents; the nature of the HTTP uniform interface is that we have a large set of documents, and a small number of messages that we can send to them.
So if you want a good resource identifier, the important thing to consider is the nature of the "document" that you are targeting with the request.
For instance, the document you are using to validate user inputs might be the validation policy; or you might instead prefer to think of that document as an index into a collection of validation reports (where we have one report available for each input).
Seems that what you try to do in the end is to run your operation in dry-run mode.
My suggestion would be to add a dry-run option as request parameter for instance.
/employee/basic?dry-run=true
REST says that you should use standards like HTTP to achieve a uniform interface. There are no URL standards as far as I know, even OData says that its URL naming conventions are optional.
Another thing that the browser is a bad REST client. REST was designed for webservices and machine to machine communication, not for the communication of browsers with webapplications, which is sort of human to machine communication. It is for solving problems like automatically order from the wholesaler to fill my webshop with new items, etc. If you check in this scenario both the REST service and REST client are on servers and have nothing to do with the browser. If you want to use REST from the browser, then it might be better to use a javascript based REST client. So using the browser with HTML forms as a REST client is something extreme.
If you have a multitab form, then it is usually collected into a session in regular webapplications until it is finalized. So one solution is having a regular webapplication, which is what you actually have, since I am pretty sure you have no idea about the mandatory REST constraints described by Fielding. In this case you just do it as you want to and forget about REST.
As of naming something that does validation I would do something like POST /employee/basic/validation and return the validation result along with 200 ok. Though most validation rules like "is it a date", "is it a number", etc. can be done on the clients currently they can be done even in HTML. You can collect the input in a session on server or client side and save it in the database after finilazing the employee description.
As of the REST way I would have a hyperlink that describes all the parameters along with their validations and let the REST client make tabs and do the REST. At the end the only time it would communicate with the REST service is when the actual POST is sent. The REST client can be in browser and collect the input into a variable or cookies or localstorage with javascript, or the REST client can be on server and collect the input into a server side session for example. As of the REST service the communication with it must be stateless, so it cannot maintain server side session, only JWT for example where all the session data is sent with every request.
If you want to save each tab in the webservice before finalizing, then your problem is something like the on that is solved with the builder design pattern in programming. In that case I would do something like POST /employeeRegistrationBuilder at the first step, and which would return a new resource something like /employeeRegistrationBuilder/1. After that I can do something like PUT/POST /employeeRegistrationBuilder/1/basics, PUT/POST /employeeRegistrationBuilder/1/education, PUT/POST /employeeRegistrationBuilder/1/workExperience, etc. and finalize it with PUT/POST /employeeRegistrationBuilder/1/finished. Though you can spare the first and the last steps and create the resource with the basics and finish it automagically after the workExperience is sent. Cancelling it would be DELETE /employeeRegistrationBuilder/1, modifying previous tabs would be PUT/PATCH /employeeRegistrationBuilder/1/basics. Removing previous tabs would be DELETE /employeeRegistrationBuilder/1/basics.
A more general approach is having a sort of transaction builder and do something like this:
POST /transactions/ {type:"multistep", method: "POST", id: "/employee/"}
-> {id: "/transactions/1", links: [...]}
PATCH /transactions/1 {append: "basics", ...}
PATCH /transactions/1 {append: "education", ...}
PATCH /transactions/1 {remove: "basics", ...}
PATCH /transactions/1 {append: "workExperience", ...}
PATCH /transactions/1 {append: "basics", ...}
...
POST /employee/ {type: "transaction", id: "/transactions/1"}
-> /employee/123
With this approach you can create a new employee both in multiple steps or in a single step depending on whether you send actual input data or a transaction reference with POST /employee.
From data protection (GDPR) perspective the transaction can be the preparation of a contract, committing the transaction can be signing the contract.

REST API - how to deal with post and functional errors

I have a REST service which is a POST to create a user, if the user does not exist, the user is created, and the service returns a 200 with the user in a json format.
Case 1: What if the user exists already, do I return a functionnal exception, so a json containing an error (all of this managed by the error handling of spring boot), and what about the http status code
Some people say to send a 303 or a 409 ... many different answers, and what about the response body in that case?
Case 2: What if in the backend we have let say a rule on the name (like containing a space) which returns an error (space not allowed in a name), same questions, do i have to return a functionnal exception and what about the http status code in this case
Somehow I want the API consumer to know what kind of json structure to handle and i guess the http status code helps for that ?
It all depends on how one interprets the various http status codes and how user friendly do you want your HTTP payload responses to be. Below are few suggestions:
NEW USER CREATED : If its a new user and gets created successfully in the backend then you return http status code 201. This is a technical status code. You can also return a functional status in the response body mentioning "User created"
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
USER ALREADY EXISTS : If the user already exists, you should respond with http status code 200 with a response payload body mentioning a functional status "User already exists"
USER CREATION FAILED : If the new user rules are not satisfied at the backend service and it throws an error then the http status code of 400 can be used and functional status in response payload of "User creation failed, please conform to the user name rules" https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400
For an API Consumer to know everything about your API's, you may want to provide a API specification document. You may use open API spec(previously known as swagger) https://swagger.io/specification/
Somehow I want the API consumer to know what kind of json structure to handle and i guess the http status code helps for that ?
Not quite.
The HTTP status code is meta data in the transfer documents over a network domain. It communicates the overall semantics of the response (for instance, is the body of the message a representation of a resource, or a representation of an error? is this response cachable? and so on).
For unsafe requests in particular, cache invalidation is sensitive to "non-error status codes". The difference between 303 (non-error status code) and 409 (error status code) can be significant.
The Content-Type header gives you a mechanism to describe the kind (schema) of the message you are returning (ex: application/problem+json).
The way I think about it: the information for your bespoke consumer belongs in the message-body; we lift data from the message-body to the HTTP metadata so that general-purpose components can take advantage of that information (for example, by invalidating cache entries).
So we would normally start by defining the schema and semantics of the message body, and making sure that we have intelligent ways to communicate all of the things we want the caller to know. In other words, we are defining the documents that we pass to the client, and how to extract information from them.
Information that HTTP components need to know get copied from our bespoke document into the standardized forms (status code, headers).
Where things get complicated: the fact that something is an "error" in your domain, that doesn't necessarily mean that it should also be considered to be an "error" in the transfer of documents over a network domain.
A common case: we are using our API to navigate some work through a process; that process has a happy path, and also some exceptional paths that we normally try to avoid (accounts are overdrawn, items are out of stock, etc).
An HTTP request can move work from the happy path to an exception path and still be a "success" in the transfer of documents domain.
The easiest heuristic I know is to think about previously cached copies of responses by the same target URI. If those responses are still re-usable, then you are probably looking at a 4xx status code. If the responses should be invalidated, then you are probably looking at a 2xx or 3xx status code.

Which HTTP status code is correct for Subscription cancel exception?

Which HTTP status code is correct for Subscription Canceled exception?
I need to throw an exception when the user tries to accesses a certain page.
I checked a few statuses like Payment Required, but it's not satisfying the requirement. Any suggestion?
Which HTTP status code is correct for Subscription cancel exception?
HTTP status codes belong to the transfer documents over a network domain.
So the specifics of what is going on in your domain don't particularly matter - the idea is to understand the error condition in terms of document transfer, and work from there.
In this case, the best fit is likely 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
It may help to imagine how this example would play out on a web site. For the human user, you would return a bunch of HTML explaining that their subscription had been cancelled, perhaps with links to resources that would allow the user to re-subscribe, and so on.
For the browser, you would have the HTTP meta data, including the status code, so that the browser would understand the general purpose semantics of the message (for instance, should earlier representations of the resource be invalidated in the cache).
it's a API request from front-end.
This doesn't really enter into the discussion; the motivation for the uniform interface is that we can swap out the implementations at either end of the conversation and the semantics of the self descriptive messages don't change.
I would say that correct Response code is:
401 Unauthorized
Since by the definition the user Cancelled his subscription and cannot more access paid content, therefore user is Unauthorized for that.
In the other words User is Authenticated but Unaouthorized to do this request.
I'd like to offer an alternative solution. 403 errors make a lot of sense here, as access is denied for a resource. However, this could be difficult to handle in the front-end, because it's indiscernible from a 403 error caused by lacking permissions or roles. A 402 error is non-standard, but "Payment Required" would be easier to program around. If using a non-standard HTTP code is allowed, I believe this to be a more suitable status to return from an API based on a cancelled subscription, or a lack of a valid subscription in general.

Best practise to write a boolean API in Java Sturts 2 server?

I need to write an API to check if a user name already exists in a database.
I want my server (Struts Action class instance in tomcat server) to return true/false.
Its something like this
checkUserName?userName=john
I want to know what is the standard way to do this?
Shall I return a JSON response with just one boolean value ... seems like a overkill.
Shall I do something like manually setting the HTTP header to 200 or 404 (for true/false), but that seems to violate the actual purpose of using the headers which I believe must only be used to indicate network failures etc.
(Too long for a comment.)
I don't see any reason not to return a standard JSON response with something indicating whether or not the user name exists. That's what APIs do: there's nothing "overkill" about providing a response useful across clients.
To your second point: headers do a lot more than "indicate network problems". A 404 isn't a network problem, it means the requested resource doesn't exist. It is not appropriate in your case, because you're not requesting a resource: the resource is checkUserName, which does exist. If instead your request was /userByName/john a 404 would be appropriate if the user didn't exist. That's not an appropriate request in this case, because you don't want to return the user.
A 401 isn't a network problem, it's an authentication issue. A 302 isn't a network problem, it's a redirect. Etc. Using HTTP response codes is entirely appropriate, if they match your requests.

How to parse a custom XML-style error code response from a website

I'm developing a program that queries and prints out open data from the local transit authority, which is returned in the form of an XML response.
Normally, when there are buses scheduled to run in the next few hours (and in other typical situations), the XML response generated by the page is handled correctly by the java.net.URLConnection.getInputStream() function, and I am able to print the individual results afterwards.
The problem is when the buses are NOT running, or when some other problem with my queries develops after it is sent to the transit authority's web server. When the authority developed their service, they came up with their own unique error response codes, which are also sent as XMLs. For example, one of these error messages might look like this:
<Error xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Code>3005</Code>
<Message>Sorry, no stop estimates found for given values.</Message>
</Error>
(This code and similar is all that I receive from the transit authority in such situations.)
However, it appears that URLConnection.getInputStream() and some of its siblings are unable to interpret this custom code as a "valid" response that I can handle and print out as an error message. Instead, they give me a more generic HTTP/1.1 404 Not Found error. This problem cascades into my program which then prints out a java.io.FileNotFoundException error pointing to the offending input stream.
My question is therefore two-fold:
1. Is there a way to retrieve, parse, and print a custom XML-formatted error code sent by a web service using the plugins that are available in Java?
2. If the above is not possible, what other tools should I use or develop to handle such custom codes as described?
URLConnection isn't up to the job of REST, in my opinion, and if you're using getInputStream, I'm almost certain you're not handling character encoding correctly.
Check out Spring's RestTemplate - it's really easy to use (just as easy as URLConnection), powerful and flexible. You will need to change the ResponseErrorHandler, because the default one will throw an exception on 404, but it looks like you want it to carry on and parse the XML in the response.

Categories

Resources