Skip to content

Commit f08542a

Browse files
committed
NFC-47 Catch errors in async IIFE. Use checkHttpError.
1 parent 9eb08a2 commit f08542a

File tree

1 file changed

+26
-36
lines changed

1 file changed

+26
-36
lines changed

example/src/main/resources/templates/webeid-login.html

Lines changed: 26 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -13,57 +13,47 @@
1313
</div>
1414

1515
<script type="module" th:inline="javascript">
16-
import { showErrorMessage } from "/js/errors.js";
16+
import {showErrorMessage, checkHttpError} from "/js/errors.js";
1717

1818
// Using an async IIFE for mobile WebView compatibility:
1919
// top-level await is not supported in some mobile browsers/WebViews.
2020
(async function () {
21-
const frag = location.hash ? location.hash.substring(1) : "";
22-
if (!frag) {
23-
showErrorMessage({ code: "UNKNOWN_ERROR", message: "Missing authentication payload" });
24-
return;
21+
const fragment = window.location.hash.slice(1);
22+
if (!fragment) {
23+
throw new Error("Missing authentication payload");
2524
}
2625

2726
let payload;
2827
try {
29-
payload = JSON.parse(atob(frag));
28+
payload = JSON.parse(atob(fragment));
3029
} catch (e) {
31-
console.error("Failed to parse payload", e);
32-
showErrorMessage({ code: "UNKNOWN_ERROR", message: "Failed to parse authentication payload" });
33-
return;
30+
console.error(e)
31+
throw new Error("Failed to parse the authentication response");
3432
}
3533

3634
if (payload.error) {
37-
showErrorMessage({
38-
code: payload.code ?? "UNKNOWN_ERROR",
39-
message: payload.message ?? "Authentication failed"
40-
});
41-
return;
35+
const error = new Error(payload.message ?? "Authentication failed");
36+
error.code = payload.code;
37+
throw error;
4238
}
4339

4440
const authToken = payload["auth_token"];
45-
46-
try {
47-
const response = await fetch(/*[[${loginProcessingPath}]]*/, {
48-
method: "POST",
49-
headers: {
50-
"Content-Type": "application/json",
51-
"X-CSRF-TOKEN": /*[[${csrfToken}]]*/
52-
},
53-
body: JSON.stringify(authToken),
54-
credentials: "include"
55-
});
56-
57-
if (!response.ok) {
58-
throw new Error("HTTP " + response.status);
59-
}
60-
61-
window.location.replace("/welcome");
62-
} catch (error) {
63-
console.error(error);
64-
showErrorMessage(error);
65-
}
66-
})();
41+
const response = await fetch(/*[[${loginProcessingPath}]]*/, {
42+
method: "POST",
43+
headers: {
44+
"Content-Type": "application/json",
45+
"X-CSRF-TOKEN": /*[[${csrfToken}]]*/
46+
},
47+
body: JSON.stringify(authToken),
48+
credentials: "include"
49+
});
50+
await checkHttpError(response);
51+
52+
window.location.replace("/welcome");
53+
})().catch((error) => {
54+
console.error(error);
55+
showErrorMessage(error);
56+
});
6757
</script>
6858
</body>
6959
</html>

0 commit comments

Comments
 (0)