Skip to content

Commit

Permalink
changed error handling and refactored some code
Browse files Browse the repository at this point in the history
  • Loading branch information
Georgi Grigorov committed Aug 15, 2024
1 parent 2b6de7c commit d88d09d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
22 changes: 13 additions & 9 deletions src/main/java/com/limechain/teavm/HttpRequest.java
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
package com.limechain.teavm;

import lombok.extern.java.Log;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.core.JSError;

import java.io.IOException;
import java.util.logging.Level;

@Log
public class HttpRequest {
@JSFunctor
interface HttpRequestCallback extends JSObject {
void apply(JSError error, String response);
}

@Async
public static native String asyncHttpRequest(String method, String url, JSObject body);
private static void asyncHttpRequest(String method, String url, JSObject body, AsyncCallback<String> callback) {
public static native String asyncHttpRequest(String method, String url, String body);

private static void asyncHttpRequest(String method, String url, String body, AsyncCallback<String> callback) {
createAsyncHttpRequest(method, url, body, (error, response) -> {
if (error != null) {
callback.error(new IOException(error.getMessage()));
log.log(Level.WARNING, error.getMessage());
} else {
callback.complete(response);
}
});
}

@JSBody(params = {"method", "url", "body", "callback"}, script = "return asyncHttpRequest(method, url, body, callback);")
public static native void createAsyncHttpRequest(String method, String url, JSObject body, HttpRequestCallback callback);
public static native void createAsyncHttpRequest(String method, String url, String body, HttpRequestCallback callback);

@JSFunctor
private interface HttpRequestCallback extends JSObject {
void apply(JSError error, String response);
}
}
6 changes: 3 additions & 3 deletions src/main/webapp/js/http.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,18 @@ async function asyncHttpRequest(method = 'GET', url, body = null, callback) {
headers: {
'Content-Type': 'application/json'
},
body: method === 'POST' ? JSON.stringify(body) : undefined
body: method === 'POST' ? body : undefined
});

if (!response.ok) {
callback(new Error(`Request failed with status: ${response?.status}`), null);
return;
}

let result = await response.text();
const result = await response.text();
callback(null, result);

} catch (error) {
callback(new Error(`Error during sending request: ${error.message}`), null);
callback(new Error(`Error during sending request: ${error?.message}`), null);
}
}

0 comments on commit d88d09d

Please sign in to comment.