Skip to content

Commit dbaf9ce

Browse files
committed
Improving error handling
1 parent f69dff5 commit dbaf9ce

File tree

3 files changed

+83
-62
lines changed

3 files changed

+83
-62
lines changed

finish/src/main/java/io/openliberty/guides/data/PackageQueryService.java

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,14 @@
3838
import jakarta.ws.rs.Path;
3939
import jakarta.ws.rs.Produces;
4040
import jakarta.ws.rs.core.MediaType;
41+
import jakarta.ws.rs.core.Response;
4142

4243
@Path("/packageQuery")
4344
public class PackageQueryService {
4445

4546
@Inject
4647
Packages packages;
4748

48-
// TODO see if some of these could be included
4949
static List<String> excludedMethods = new ArrayList<String>();
5050
static {
5151
excludedMethods.add("add");
@@ -112,10 +112,11 @@ public String queries() {
112112
@SuppressWarnings("unchecked")
113113
@POST
114114
@Consumes(MediaType.APPLICATION_JSON)
115-
@Produces(MediaType.APPLICATION_JSON)
116-
public String callQuery(String jsonString) {
115+
@Produces({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
116+
public Response callQuery(String jsonString) {
117117
System.out.println(jsonString);
118118
JsonObject json = Json.createReader(new StringReader(jsonString)).readObject();
119+
JsonArrayBuilder returnList = Json.createArrayBuilder();
119120
try {
120121
List<Object> params = new ArrayList<Object>();
121122
List<Class<?>> types = new ArrayList<Class<?>>();
@@ -130,8 +131,9 @@ public String callQuery(String jsonString) {
130131
types.add(Class.forName(type));
131132
}
132133
} catch (ClassNotFoundException e) {
133-
// TODO Reply to Client with error message
134134
e.printStackTrace();
135+
return Response.status(404).type(MediaType.TEXT_PLAIN)
136+
.entity("The requested Query does not exist.").build();
135137
}
136138
params.add(getTypedValue(jsonParams, i, types.get(i)));
137139
}
@@ -141,7 +143,6 @@ public String callQuery(String jsonString) {
141143
checkForID(method, params);
142144
Object result = method.invoke(packages, params.toArray());
143145

144-
JsonArrayBuilder returnList = Json.createArrayBuilder();
145146
if (result instanceof Stream) {
146147
((Stream<?>) result).forEach(p -> {
147148
returnList.add(((Package) p).toJson());
@@ -157,19 +158,25 @@ public String callQuery(String jsonString) {
157158
"Return type " + result.getClass()
158159
+ " not handled in PackageQueryService.java");
159160
}
160-
return returnList.build().toString();
161161
} catch (NoSuchMethodException | SecurityException | IllegalAccessException
162162
| IllegalArgumentException | InvocationTargetException e) {
163-
// TODO Reply to Client with error message
164-
e.printStackTrace();
165-
166163
if (e instanceof InvocationTargetException) {
167164
if (e.getCause() != null) {
168-
return e.getCause().toString();
165+
return Response.status(404).type(MediaType.TEXT_PLAIN)
166+
.entity(e.getCause().toString()).build();
169167
}
168+
} else if (e instanceof IllegalArgumentException) {
169+
return Response.status(404).type(MediaType.TEXT_PLAIN)
170+
.entity("Invalid input for selected method. " + e.getMessage())
171+
.build();
172+
} else {
173+
e.printStackTrace();
174+
return Response.status(404).type(MediaType.TEXT_PLAIN)
175+
.entity("Error. " + e.getMessage()).build();
170176
}
171177
}
172-
return "";
178+
return Response.ok(returnList.build().toString(), MediaType.APPLICATION_JSON)
179+
.build();
173180
}
174181

175182
Object getTypedValue(JsonArray array, int index, Class<?> type) {
@@ -212,14 +219,12 @@ Limit parseLimit(String limit) {
212219
} else {
213220
return Limit.of(Integer.parseInt(limit));
214221
}
215-
// TODO catch java.lang.NumberFormatException and return error message to user
216222
}
217223

224+
// TODO handle pagerequest
218225
PageRequest parsePageRequest(String page, String maxPageLength) {
219226
return PageRequest.ofPage(Long.parseLong(page), Integer.parseInt(maxPageLength),
220227
false);
221-
// TODO catch java.lang.NumberFormatException and return error message to user
222-
223228
}
224229

225230
// Due to type erasure we need to handle id as a special case

finish/src/main/webapp/js/app.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ async function callQuery(index) {
8282
headers: {
8383
"Content-Type": "application/json"
8484
},
85+
8586
body: JSON.stringify(query),
8687
})
8788

@@ -122,7 +123,8 @@ async function processResponse(response) {
122123
}
123124
}
124125
} else {
125-
toast("Error! TODO better message", 0)
126+
const message = await response.text();
127+
toast(message, 0)
126128
}
127129

128130
console.log(response);
@@ -153,7 +155,7 @@ function sortDropDown(options) {
153155
}
154156

155157
function toast(message, index) {
156-
var length = 3000;
158+
var length = 6000;
157159
var toast = document.getElementById("toast");
158160
setTimeout(function () { toast.innerText = message; toast.className = "show"; }, length * index);
159161
setTimeout(function () { toast.className = toast.className.replace("show", ""); }, length + length * index);

start/src/main/webapp/js/app.js

Lines changed: 60 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ async function loadQueries() {
1010
function addToQueries(item, index) {
1111
var container = document.createElement("div")
1212
container.id = "query" + index
13-
container.className = "vFlexContainer queryElement"
13+
container.className = "hFlexContainer queryElement"
1414

15-
var parameters = document.createElement("div")
16-
parameters.className = "hFlexContainer"
15+
16+
var span = document.createElement("span")
17+
span.innerHTML = item.name
18+
container.appendChild(span)
1719

1820
item.parameters.forEach((param, index) => {
1921
if (item.types[index] == "jakarta.data.Sort") {
@@ -23,103 +25,115 @@ function addToQueries(item, index) {
2325
input.placeholder = param
2426
}
2527
input.setAttribute("jtype", item.types[index])
26-
parameters.appendChild(input)
28+
container.appendChild(input)
2729
})
2830

29-
container.appendChild(parameters)
30-
3131
var button = document.createElement("button")
32-
button.setAttribute("onclick","callQuery(" + index + ")")
33-
button.innerHTML = item.name
32+
button.setAttribute("onclick", "callQuery(" + index + ")")
33+
button.alt = "Run the " + item.name + "query"
34+
button.innerHTML = "➜"
3435

3536
container.appendChild(button)
3637

3738
var node = document.getElementById("querySection")
3839
node.appendChild(container)
39-
40-
}
40+
41+
}
4142

4243
async function callQuery(index) {
4344
var node = document.getElementById("query" + index)
44-
45+
4546
var query = {}
46-
query.method = node.getElementsByTagName("button")[0].innerHTML
47-
var inputs = node.getElementsByTagName("div")[0]
47+
query.method = node.querySelector("span").innerHTML
4848

4949
//Process Inputs
5050
var params = []
5151
var types = []
52-
console.log(inputs.children)
53-
console.log(Array.from(inputs.children))
54-
Array.from(inputs.children).forEach(input => {
52+
console.log(node)
53+
54+
console.log(node.children)
55+
console.log(Array.from(node.children))
56+
Array.from(node.children).forEach(input => {
5557
console.log(input.tagName)
5658
if (input.tagName == "INPUT") { //input
57-
params.push(input.value)
59+
params.push(input.value)
60+
types.push(input.getAttribute("jtype"))
5861
} else if (input.tagName == "DIV") { //sort
5962
var text = ""
6063
input.childNodes.forEach(select => {
61-
if (text == "")
64+
if (text == "")
6265
text = select.options[select.selectedIndex].text
6366
else text = text + " " + select.options[select.selectedIndex].text
64-
})
67+
})
6568
params.push(text)
69+
types.push(input.getAttribute("jtype"))
6670
}
67-
types.push(input.getAttribute("jtype"))
71+
6872
})
6973

74+
7075
query.parameters = params
7176
query.types = types
77+
console.log(query)
7278

7379
//Return json object
7480
const response = await fetch("shipping/packageQuery", {
75-
method: "POST",
76-
headers: {
77-
"Content-Type": "application/json"
78-
},
79-
body: JSON.stringify(query),
80-
})
81+
method: "POST",
82+
headers: {
83+
"Content-Type": "application/json"
84+
},
85+
86+
body: JSON.stringify(query),
87+
})
8188

8289
processResponse(response)
8390
}
8491

8592

8693
async function processResponse(response) {
87-
if (response.ok) {
88-
const body = await response.text();
94+
if (response.ok) {
95+
const body = await response.text();
8996
console.log(body)
90-
if (body.length > 0) {
97+
if (body.length > 0) {
9198
var node = document.getElementById("resultsSection")
92-
node.replaceChildren() //clear the results section
99+
node.style = "" //Make the results section visible
93100

94101
try { //Return useful server exception to user
95102
var json = JSON.parse(body)
103+
console.log(json)
96104
} catch (error) {
97105
var div = document.createElement("div")
98106
div.innerHTML = body
99107
node.appendChild(div)
100108
}
101109

110+
var table = document.getElementById("tableBody")
111+
var length = table.rows.length
112+
for (let i = 0; i < length; i++) table.deleteRow(0) //clear table
113+
114+
console.log("removed table")
102115
for (m of json) {
103-
var div = document.createElement("div")
104-
div.innerHTML = "id = " + m.id;
105-
div.innerHTML += " length = " + m.length;
106-
div.innerHTML += " width = " + m.width;
107-
div.innerHTML += " height = " + m.height;
108-
div.innerHTML += " destination = " + m.destination;
109-
node.appendChild(div)
116+
console.log("inserting row")
117+
var row = table.insertRow()
118+
row.insertCell().innerHTML = m.id;
119+
row.insertCell().innerHTML = m.length;
120+
row.insertCell().innerHTML = m.width;
121+
row.insertCell().innerHTML = m.height;
122+
row.insertCell().innerHTML = m.destination;
110123
}
111-
}
112-
} else {
113-
toast("Error! TODO better message",0)
114-
}
124+
}
125+
} else {
126+
const message = await response.text();
127+
toast(message, 0)
128+
}
115129

116130
console.log(response);
117131
}
118132

119133
function sortDropDown(options) {
120134
var div = document.createElement("div")
121135
var params = document.createElement("select")
122-
136+
123137
var options = ["id", "length", "width", "height", "destination"]
124138
options.forEach(input => {
125139
var option = document.createElement("option")
@@ -141,8 +155,8 @@ function sortDropDown(options) {
141155
}
142156

143157
function toast(message, index) {
144-
var length = 3000;
145-
var toast = document.getElementById("toast");
146-
setTimeout(function(){ toast.innerText = message; toast.className = "show"; }, length*index);
147-
setTimeout(function(){ toast.className = toast.className.replace("show",""); }, length + length*index);
158+
var length = 6000;
159+
var toast = document.getElementById("toast");
160+
setTimeout(function () { toast.innerText = message; toast.className = "show"; }, length * index);
161+
setTimeout(function () { toast.className = toast.className.replace("show", ""); }, length + length * index);
148162
}

0 commit comments

Comments
 (0)