下面列出了怎么用com.google.gwt.core.client.JavaScriptException的API类实例代码及写法,或者点击链接到github查看源代码。
@NotNull
@Override
public Promise<WebRTCSessionDescription> setRemoteDescription(@NotNull final WebRTCSessionDescription description) {
return new Promise<>(new PromiseFunc<WebRTCSessionDescription>() {
@Override
public void exec(@NotNull final PromiseResolver<WebRTCSessionDescription> resolver) {
peerConnection.setRemoteDescription(JsSessionDescription.create(description.getType(),
description.getSdp()), new JsClosure() {
@Override
public void callback() {
resolver.result(description);
}
}, new JsClosureError() {
@Override
public void onError(JavaScriptObject error) {
resolver.error(new JavaScriptException(error));
}
});
}
});
}
private static void doReportStacktrace(Exception exception) {
// Defer without $entry to bypass some of GWT's exception handling
deferWithoutEntry(() -> {
// Bypass regular exception reporting
UncaughtExceptionHandler originalHandler = GWT
.getUncaughtExceptionHandler();
GWT.setUncaughtExceptionHandler(
ignore -> GWT.setUncaughtExceptionHandler(originalHandler));
// Throw in the appropriate way
if (exception instanceof JavaScriptException) {
// Throw originally thrown instance through JS
jsThrow(((JavaScriptException) exception).getThrown());
} else {
throw exception;
}
});
}
private void onBeforeUnload(Event event) {
captureCurrentScrollPositions();
JsonObject stateObject = createStateObjectWithHistoryIndexAndToken();
JsonObject sessionStorageObject = Json.createObject();
sessionStorageObject.put(X_POSITIONS,
convertArrayToJsonArray(xPositions));
sessionStorageObject.put(Y_POSITIONS,
convertArrayToJsonArray(yPositions));
Browser.getWindow().getHistory().replaceState(stateObject, "",
Browser.getWindow().getLocation().getHref());
try {
Browser.getWindow().getSessionStorage().setItem(
createSessionStorageKey(historyResetToken),
sessionStorageObject.toJson());
} catch (JavaScriptException e) {
Console.error("Failed to get session storage: " + e.getMessage());
}
}
private static XMLHttpRequest request(XMLHttpRequest xhr, String method,
String url, String requestData, String contentType,
Callback callback) {
try {
xhr.setOnReadyStateChange(new Handler(callback));
xhr.open(method, url);
xhr.setRequestHeader("Content-type", contentType);
xhr.setWithCredentials(true);
xhr.send(requestData);
} catch (JavaScriptException e) {
// Just fail.
Console.error(e);
callback.onFail(xhr, e);
xhr.clearOnReadyStateChange();
}
return xhr;
}
public void load() {
String item = localStorage.getItem(documentsKey());
if (item != null) {
idCounter = Long.parseLong(item);
}
try {
loadInternal(indexKey());
if (indexRef == null) {
// no index found in local storage
reset();
} else {
Log.info("Loaded " + idCounter + " documents from index at " + indexKey());
}
} catch (JavaScriptException e) {
// load must be fail safe, so ignore any errors and reset
reset();
}
}
/**
* Load the blocks described by blocksContent into the blocks workspace.
*
* @param formJson JSON description of Form's structure for upgrading
* @param blocksContent XML description of a blocks workspace in format expected by Blockly
* @throws LoadBlocksException if Blockly throws an uncaught exception
*/
// [lyn, 2014/10/27] added formJson for upgrading
public void loadBlocksContent(String formJson, String blocksContent) throws LoadBlocksException {
try {
doLoadBlocksContent(formJson, blocksContent);
} catch (JavaScriptException e) {
loadError = true;
ErrorReporter.reportError(MESSAGES.blocksLoadFailure(formName));
OdeLog.elog("Error loading blocks for screen " + formName + ": "
+ e.getDescription());
throw new LoadBlocksException(e, formName);
} finally {
loadComplete = true;
}
}
/**
* Get Yail code for current blocks workspace
*
* @return the yail code as a String
* @throws YailGenerationException if there was a problem generating the Yail
*/
public String getYail(String formJson, String packageName) throws YailGenerationException {
try {
return doGetYail(formJson, packageName);
} catch (JavaScriptException e) {
throw new YailGenerationException(e.getDescription(), formName);
}
}
public void sendComponentData(String formJson, String packageName, boolean force) throws YailGenerationException {
if (!currentForm.equals(formName)) { // Not working on the current form...
OdeLog.log("Not working on " + currentForm + " (while sending for " + formName + ")");
return;
}
try {
doSendJson(formJson, packageName, force);
} catch (JavaScriptException e) {
throw new YailGenerationException(e.getDescription(), formName);
}
}
@NotNull
@Override
public Promise<WebRTCSessionDescription> setLocalDescription(@NotNull final WebRTCSessionDescription description) {
return new Promise<>(new PromiseFunc<WebRTCSessionDescription>() {
@Override
public void exec(@NotNull final PromiseResolver<WebRTCSessionDescription> resolver) {
peerConnection.setLocalDescription(JsSessionDescription.create(description.getType(), description.getSdp()), () -> {
resolver.result(description);
}, error -> resolver.error(new JavaScriptException(error)));
}
}
);
}
private void readAndRestoreScrollPositionsFromHistoryAndSessionStorage(
boolean delayAfterResponse) {
// restore history index & token from state if applicable
JsonObject state = (JsonObject) Browser.getWindow().getHistory()
.getState();
if (state != null && state.hasKey(HISTORY_INDEX)
&& state.hasKey(HISTORY_TOKEN)) {
currentHistoryIndex = (int) state.getNumber(HISTORY_INDEX);
historyResetToken = state.getNumber(HISTORY_TOKEN);
String jsonString = null;
try {
jsonString = Browser.getWindow().getSessionStorage()
.getItem(createSessionStorageKey(historyResetToken));
} catch (JavaScriptException e) {
Console.error(
"Failed to get session storage: " + e.getMessage());
}
if (jsonString != null) {
JsonObject jsonObject = Json.parse(jsonString);
xPositions = convertJsonArrayToArray(
jsonObject.getArray(X_POSITIONS));
yPositions = convertJsonArrayToArray(
jsonObject.getArray(Y_POSITIONS));
// array lengths checked in restoreScrollPosition
restoreScrollPosition(delayAfterResponse);
} else {
Console.warn(
"History.state has scroll history index, but no scroll positions found from session storage matching token <"
+ historyResetToken
+ ">. User has navigated out of site in an unrecognized way.");
resetScrollPositionTracking();
}
} else {
resetScrollPositionTracking();
}
}
private static XMLHttpRequest request(XMLHttpRequest xhr, String method,
String url, final Callback callback) {
try {
xhr.setOnReadyStateChange(new Handler(callback));
xhr.open(method, url);
xhr.send();
} catch (JavaScriptException e) {
// Just fail.
Console.error(e);
callback.onFail(xhr, e);
xhr.clearOnReadyStateChange();
}
return xhr;
}
/**
* Create a JsonMessage object from the given json
* @param json The JSON String to load from.
* @return true if evaluation is successful, false otherwise.
*/
public static JsonMessage createJsonMessage(String json) throws JsonException {
try {
JsonMessage obj = (JsonMessage) serializer.parse(json);
registerNativeJsonMessageToString(obj);
return obj;
} catch (JavaScriptException e) {
throw new JsonException(e);
}
}
/**
* Create a JsonMessage object from the given json
* @param json The JSON String to load from.
* @return true if evaluation is successful, false otherwise.
*/
public static JsonMessage createJsonMessage(RawStringData data) throws JsonException {
try {
JsonMessage obj = (JsonMessage) serializer.parse(data.getBaseString());
JsonHelper.registerRawStringData(obj, data);
registerNativeJsonMessageToString(obj);
return obj;
} catch (JavaScriptException e) {
throw new JsonException(e);
}
}
public final void setAnchorAndFocus(Node anchorNode, int anchorOffset,
Node focusNode, int focusOffset) {
if (QuirksConstants.HAS_BASE_AND_EXTENT) {
// NOTE(danilatos): While extend() would also work for webkit,
// we have to use setBaseAndExtent because it appears to reuse
// the existing range, rather than needing to replace it, and
// doing otherwise stuffs up the IME composition state
setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
} else {
// We assume that anchor node is in the same focusable area.
// If not, death will ensue.
setFocusElement(focusNode);
// TODO(danilatos): Investigate just using extend() twice - i.e.
// extend to the anchor -> collapse to end -> extend to the focus.
JsRange range = JsRange.create();
range.setStart(anchorNode, anchorOffset);
range.collapse(true);
removeAllRanges();
addRange(range);
if (focusNode != anchorNode || focusOffset != anchorOffset) {
try {
extend(focusNode, focusOffset);
} catch (JavaScriptException e) {
NativeSelectionUtil.LOG.error().logPlainText(
"error extending selection from " + anchorNode + ":" + anchorOffset +
" to " + focusNode + ":" + focusOffset);
removeAllRanges();
range = JsRange.create();
range.setStart(anchorNode, anchorOffset);
range.collapse(true);
range.setEnd(focusNode, focusOffset);
addRange(range);
}
}
}
}
@Override
PointRange<Node> getOrdered() {
// NOTE(user): try/catch here as JsTextRangeIE.duplicate throws an exception if the
// selection is non-text, i.e. an image. Its much safer to wrap these IE native methods.
// TODO(user): Decide whether returning null is the correct behaviour when exception is
// thrown. If so, remove the logger.error().
try {
// Get selection + corresponding text range
JsSelectionIE selection = JsSelectionIE.get();
JsTextRangeIE start = selection.createRange();
// Best test we have found for empty selection
if (checkNoSelection(selection, start)) {
return null;
}
// create two collapsed ranges, for each end of the selection
JsTextRangeIE end = start.duplicate();
start.collapse(true);
end.collapse(false);
// Translate to HtmlPoints
Point<Node> startPoint = pointAtCollapsedRange(start);
return JsTextRangeIE.equivalent(start, end) ? new PointRange<Node>(startPoint)
: new PointRange<Node>(startPoint, pointAtCollapsedRange(end));
} catch (JavaScriptException e) {
logger.error().log("Cannot get selection", e);
return null;
}
}
private void setHeaders(Headers headers, XMLHttpRequest xmlHttpRequest) throws JavaScriptException {
if (headers != null && headers.size() > 0) {
for (Header header : headers) {
xmlHttpRequest.setRequestHeader(header.getName(), header.getValue());
}
}
}
@Override
public void auth(PreparedRequest preparedRequest) {
try {
preparedRequest.setHeader("Authorization", "Basic " + btoa(user + ":" + password));
} catch (JavaScriptException e) {
throw new UnsupportedOperationException("It was not possible to encode credentials using browser's " +
"native btoa. The browser does not support this operation.", e);
}
preparedRequest.setWithCredentials(withCredentials);
preparedRequest.send();
}
/**
* Create a JsonMessage object from the given json
* @param json The JSON String to load from.
* @return true if evaluation is successful, false otherwise.
*/
public static JsonMessage createJsonMessage(String json) throws JsonException {
try {
JsonMessage obj = (JsonMessage) serializer.parse(json);
registerNativeJsonMessageToString(obj);
return obj;
} catch (JavaScriptException e) {
throw new JsonException(e);
}
}
/**
* Create a JsonMessage object from the given json
* @param json The JSON String to load from.
* @return true if evaluation is successful, false otherwise.
*/
public static JsonMessage createJsonMessage(RawStringData data) throws JsonException {
try {
JsonMessage obj = (JsonMessage) serializer.parse(data.getBaseString());
JsonHelper.registerRawStringData(obj, data);
registerNativeJsonMessageToString(obj);
return obj;
} catch (JavaScriptException e) {
throw new JsonException(e);
}
}
public final void setAnchorAndFocus(Node anchorNode, int anchorOffset,
Node focusNode, int focusOffset) {
if (QuirksConstants.HAS_BASE_AND_EXTENT) {
// NOTE(danilatos): While extend() would also work for webkit,
// we have to use setBaseAndExtent because it appears to reuse
// the existing range, rather than needing to replace it, and
// doing otherwise stuffs up the IME composition state
setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
} else {
// We assume that anchor node is in the same focusable area.
// If not, death will ensue.
setFocusElement(focusNode);
// TODO(danilatos): Investigate just using extend() twice - i.e.
// extend to the anchor -> collapse to end -> extend to the focus.
JsRange range = JsRange.create();
range.setStart(anchorNode, anchorOffset);
range.collapse(true);
removeAllRanges();
addRange(range);
if (focusNode != anchorNode || focusOffset != anchorOffset) {
try {
extend(focusNode, focusOffset);
} catch (JavaScriptException e) {
NativeSelectionUtil.LOG.error().logPlainText(
"error extending selection from " + anchorNode + ":" + anchorOffset +
" to " + focusNode + ":" + focusOffset);
removeAllRanges();
range = JsRange.create();
range.setStart(anchorNode, anchorOffset);
range.collapse(true);
range.setEnd(focusNode, focusOffset);
addRange(range);
}
}
}
}
@Override
PointRange<Node> getOrdered() {
// NOTE(user): try/catch here as JsTextRangeIE.duplicate throws an exception if the
// selection is non-text, i.e. an image. Its much safer to wrap these IE native methods.
// TODO(user): Decide whether returning null is the correct behaviour when exception is
// thrown. If so, remove the logger.error().
try {
// Get selection + corresponding text range
JsSelectionIE selection = JsSelectionIE.get();
JsTextRangeIE start = selection.createRange();
// Best test we have found for empty selection
if (checkNoSelection(selection, start)) {
return null;
}
// create two collapsed ranges, for each end of the selection
JsTextRangeIE end = start.duplicate();
start.collapse(true);
end.collapse(false);
// Translate to HtmlPoints
Point<Node> startPoint = pointAtCollapsedRange(start);
return JsTextRangeIE.equivalent(start, end) ? new PointRange<Node>(startPoint)
: new PointRange<Node>(startPoint, pointAtCollapsedRange(end));
} catch (JavaScriptException e) {
logger.error().log("Cannot get selection", e);
return null;
}
}
private void doExecute(Runnable r) {
try {
r.run();
} catch (JavaScriptException jse) {
if (jse.isThrownSet()) {
LOG.severe("Caught JavaScriptException, wrapped error is: " + jse.getThrown());
}
ThrowableHandlers.handle(jse);
} catch (Throwable t) {
ThrowableHandlers.handle(t);
}
}
public LoadBlocksException(JavaScriptException e, String formName) {
super(e);
this.formName = formName;
}
/**
* IE-specific trick to keep an empty paragraph "open" (i.e. prevent it from
* collapsing to zero height). See class javadoc for details.
*
* Since we know of no direct way to set the magic flag, we mimic the user
* deleting the last char.
*
* TODO(user): can we get away with only doing this when creating new, empty
* paragraphs? It seems our own emptying should already set the magic flag,
* but for some reason it doesn't seem to happen...
*
* NB(user): The flag only gets set when the nodelet is attached to the
* editor. See also ImplementorImpl.Helper#beforeImplementation(Element)
*/
public static void openEmptyParagraph(Element nodelet) {
// Add + delete an arbitrary char from the paragraph
// TODO(user): why does this throw exception in <caption> elements?
try {
Point<Node> point = IeNodeletHelper.beforeImplementation(nodelet);
nodelet.setInnerHTML("x");
nodelet.setInnerHTML("");
IeNodeletHelper.afterImplementation(nodelet, point);
} catch (JavaScriptException t) {}
}
/**
* IE-specific trick to keep an empty paragraph "open" (i.e. prevent it from
* collapsing to zero height). See class javadoc for details.
*
* Since we know of no direct way to set the magic flag, we mimic the user
* deleting the last char.
*
* TODO(user): can we get away with only doing this when creating new, empty
* paragraphs? It seems our own emptying should already set the magic flag,
* but for some reason it doesn't seem to happen...
*
* NB(user): The flag only gets set when the nodelet is attached to the
* editor. See also ImplementorImpl.Helper#beforeImplementation(Element)
*/
public static void openEmptyParagraph(Element nodelet) {
// Add + delete an arbitrary char from the paragraph
// TODO(user): why does this throw exception in <caption> elements?
try {
Point<Node> point = IeNodeletHelper.beforeImplementation(nodelet);
nodelet.setInnerHTML("x");
nodelet.setInnerHTML("");
IeNodeletHelper.afterImplementation(nodelet, point);
} catch (JavaScriptException t) {}
}
/**
* Get a Date object mapped to the specified key.
*
* @param key The name of the Date property.
* @return A Date object, or null if the key is not found.
* @throws com.google.gwt.core.client.JavaScriptException if the key is found but the object returned
* is not a Date.
* @throws TypeException If the key is found but the value is not an object.
*/
public final Date getDate(String key)
throws JavaScriptException, TypeException {
return JsDate.toJava((JsDate) getObject(key));
}