Hi everyone.
I have a question, little off topic but would like to hear your feedback/best practice and how you handle that. I am reading a little bit about clean code and found some methods where i return null in a method, which should be avoided in terms of clean code.
Imagine you have a Vaadin View. This View has a Rest API service injected and calls an external API. This API returns an object or thows errors when there is a problem in the API.
How do you handle messages/errors" to return them from the service back to the frontend layer to show kind of “user friendly” message
(following is dummycode)
class MyView {
//Vaadin View implementatoin
RestClient restClient;
//inject Restclient
Button button = new Button ("Get Data");
button.addClickListener {
MyObject myObj = restClient.getData();
if(myObj.getSuccess){
//use object
} else {
if(myObj.getMessage.contains(XY))
Notification.ErrorNotifitcation("Error xy").show();
}
}
}
Currently i wrap it in a class like:
public class CustomResonse {
private MyObject obj;
private boolean success;
private String message;
}
public class RestClient {
public MyObject getData() {
return restClient.post()
.uri(baseUrl + "/externalEndpoint")
.headers(httpHeaders -> {
httpHeaders.set("Content-Type", "application/json");
httpHeaders.set("Authorization", "Bearer " + validatedToken);
})
.body(body)
.exchange((req, res) -> {
try {
if (res.getStatusCode().is2xxSuccessful()) {
MyObject mo = new MyObject();
mo.setSuccess(true);
return mo;
}
} catch (HttpClientErrorException e) {
e.printStackTrace();
MyObject mo = new MyObject();
mo.setSuccess(false);
mo.setMessage("error from exception");
return mo;
} catch (IOException re) {
MyObject mo = new MyObject();
mo.setSuccess(false);
mo.setMessage("error from exception");
return mo;
} catch (ResourceAccessException re) {
MyObject mo = new MyObject();
mo.setSuccess(false);
mo.setMessage("error from exception");
return mo;
}
MyObject mo = new MyObject();
mo.setSuccess(false);
mo.setMessage("error from exception");
return mo;
});
}
}
Would love to get your best practice :)