while looking for a simple way to display errors I've found SwingX
Currently I'm using
JXErrorPane.showDialog(null, new ErrorInfo("Error", e.getMessage(), null, null, exception, ErrorLevel.SEVERE, null));
which results in the following : http://i.imgur.com/JKeF4.png
I really like the way this looks but I don't want to show the stack trace. I've tried passing null instead of the exception but that way I don't get the details.
Is there any way to just omit the stack trace?
(Like this : http://i.imgur.com/kObaH.png)
If you don't like the auto-built details message (which is built by the BasicErrorPaneUI, have a look at its getDetailsAsHtml), you can pass-in a custom one like:
Exception e = new NullPointerException("something ...");
// copied from BasicErrorPaneUI
StringBuffer html = new StringBuffer("<html>");
html.append("<h2>" + "Error" + "</h2>");
html.append("<HR size='1' noshade>");
html.append("<div></div>");
html.append("<b>Message:</b>");
html.append("<pre>");
html.append(" " + e.toString());
html.append("</pre>");
html.append("<b>Level:</b>");
html.append("<pre>");
html.append(" " + ErrorLevel.SEVERE);
html.append("</pre>");
html.append("</html>");
ErrorInfo errorInfo = new ErrorInfo("Error", e.getMessage(),
html.toString(), null, e, ErrorLevel.SEVERE, null);
JXErrorPane.showDialog(null, errorInfo);
If you want to do that more often, I would suggest a custom ErrorInfo subclass
Related
There are a lot of if-else statements in my code what is the best way that I can avoid so many if-else statements. Below is the code snippet. Now again I need to check if WWW-Authenticate header returns value
signature_invalid
then I need to log and return a different error message and if WWW-Authenticate header returns value
token_exppured
then I need to log a different error message which will again add 2 more ifs. Can anyone Help me how can I avoid this??
if (e.getRawStatusCode() == NOT_FOUND) {
logger.log(
log,
LogLevel.ERROR,
MISSING_VALID_ID_ERROR_MSG + " : " + e.toString(),
viewRequest);
String errorDetails = createNotFoundDetails(appl, transactionId);
updateIdentifier(rcvLog, true, request, identifier);
return createErrorViewResponseReply(MISSING_VALID_ID_ERROR_MSG, errorDetails);
} else if (e.getRawStatusCode() == UNAUTHORIZED) {
logger.log(
log,
LogLevel.ERROR,
UNABLE_TO_REACH_ERROR_MSG + " : " + e.toString(),
viewRequest);
if (e.getResponseHeaders() != null && e.getResponseHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE != null)) {
logger.log(
log,
LogLevel.ERROR,
INVALID_TOKEN_ERROR_MSG + " : " + e.getResponseHeaders().getFirst(HttpHeaders.WWW_AUTHENTICATE),
viewRequest);
}
updateIdentifier(rcvLog, false, request, identifier);
return createErrorViewResponseReply(
UNABLE_TO_REACH_ERROR_MSG,
INVALID_TOKEN_ERROR_DETAILS);
}
The basic approaches one can take with this is:
Create a class hierarchy with a factory to instantiate the right instance to respond to the action
Do the same but in short hand with Enums
Use a map of this::method() and call your methods that do the work for you
For your case, since you can't really control the types of code an API sends you, and a factory method may be overkill, a map approach may be best:
map.put(NOT_FOUND, this::methodA);
map.put(UNAUTHORIZED, this::methodB);
map.put(OTHER, this::methodC);
map.computeIfAbsent(
e.getRawStatusCode(),
(e, rc, req, id) -> {/** NOTHING */}
).apply(e, rcvLog, request, identifier);
computeIfAbsent() allows you to handle the unhandled case with basically a no-op.
I need to raise a warning during one of my scenario but i don't stop to have this error appearing : "Cannot infer type arguments for Result.Warning<>"
I actually tried to raise the Warning the same way i was raising Failure until now :
new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, oscarAccesClientPage.getCallBack());
The custom step i am using it inside is the following : I'm trying to go over a list of Element and checking that the existing value of them is the same or not as the one saved before.
protected void checkXyResourcesValue(Integer xyIterator, List<WebElement> elements, String keyParameter) throws TechnicalException, FailureException {
try {
Integer resIterator = 1;
for(WebElement element : elements) {
String targetKey = "XY" + xyIterator + "RES" + resIterator + keyParameter;
String new_value = element.getAttribute(VALUE) != null ? element.getAttribute(VALUE) : element.getText();
String existing_value = Context.getValue(targetKey) != null ? Context.getValue(targetKey) : targetKey;
if (new_value != existing_value) {
new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, oscarAccesClientPage.getCallBack());
}
resIterator++;
}
} catch (Exception e) {
new Result.Failure<>(e.getMessage(), Messages.format(TaroMessages.FAIL_MESSAGE_ACCES_CLIENT_XY_CHECK_RESOURCES_VALUE, keyParameter, xyIterator), true, oscarAccesClientPage.getCallBack());
}
}
For the method to check and saved value I actually inspired myself for the piece of code from NoraUI to save a value on Context or read it from.
I'm using Eclipse Luna 4.4.2 and i try to compile using JDK1.8.0_131.
It may be more related to me not knowing how this work in Java than a real problem so thank you in advance for your help or insights. Don't hesitate to ask if you need more information on the piece of code or the context.
new Result.Warning<>(targetKey, Messages.format(TaroMessages.WARNING_RESOURCES_VALUE_DIFFERENCE_AFTER_REAFFECTATION, existing_value, new_value), true, 0);
use 0 if you do not use any Model (data serialized) or use id of your Object in the serial.
In case of bulkWrite(), I want array of _ids of successfully processed documents OR failed documents, along with reason for failure.
Following is the attempt I made. Suggest more easy approach if possible.
try {
collection.insertMany(documents, new InsertManyOptions().ordered(false));
} catch (DuplicateKeyException dke) {
LOGGER.error("{}", dke);
} catch (MongoBulkWriteException mbwe) {
List<BulkWriteError> errors = mbwe.getWriteErrors();
for (BulkWriteError error : errors) {
LOGGER.error("{}", error.getMessage());
}
} catch (Exception ex) {
LOGGER.error("{}", ex.getCause());
}
When I insert document with duplicate _ids, I supposed to get DuplicateKeyException as per javadoc, but I am getting MongoBulkWriteException.
I am using java 8 and mongodb 3.2.1 drivers
insertMany throws only the following exceptions:
MongoBulkWriteException - if there's an exception in the bulk write operation
MongoException - if the write failed due some other failure
However the exception carries the cause of it and in the case of a duplicated id will be something like:
insertDocument :: caused by :: 11000 E11000 duplicate key error index: test.restaurants.$_id_ dup key: { : ObjectId('56c8ac3146235e4898bb696c') }
So since you have the information in the message you can extract with a regular expression the ids of the documents that failed in an array.
The code would be something like that (I am giving it inline in your code):
List<String>duplicateIds = new ArrayList<String>();
List<BulkWriteError> errors = mbwe.getWriteErrors();
for (BulkWriteError error : errors) {
LOGGER.error("{}", error.getMessage());
// extract from error.message the id of the duplicated document, (11000 is the duplicate id code)
if (error.getCode() == 11000) {
Matcher m = Pattern.compile("[0-9a-f]{24}")
.matcher(error.getMessage());
m.find();
duplicateIds.add(m.group());
}
}
// here the duplicateIds will hold all the found ids, you can print them in console for example:
System.out.println(duplicateIds.toString());
// and do whatever else you like with them
The above code will catch the duplicated Ids - if you want to make it to catch other errors it is easy to adapt it accordingly.
UPDATE:
If you want to use bulkWrite() you can use exactly the same code since it throws the same exceptions (MongoBulkWrite, MongoException) as insertMany(), see BulkWrite()
If you want to update the code to catch other exceptions it is easily expandable:
see what the specific message and error code is for the exception you want to catch from the logs.
add an if block as the one I gave for that particular error code to extract the ids with a regular expression and add them to the array you have initialized for that kind of error
do your handling in the end
Part of the code:
Rengine re = getRengine();
re.eval("library(quantmod)");
re.eval("library(PerformanceAnalytics)");
re.eval("library(tseries)");
re.eval("library(FinTS)");
re.eval("library(rugarch)");
re.eval("library(robustbase)");
re.assign("arLagNum", new double[]{1});
re.assign("maLagNum", new double[]{1});
re.assign("archLagNum", new double[]{1});
re.assign("garchLagNum", new double[]{1});
re.eval("garchSpec <- ugarchspec(variance.model = list(model=\"iGARCH\", garchOrder=c(archLagNum,garchLagNum)), mean.model = list(armaOrder=c(arLagNum,maLagNum)), distribution.model=\"std\")");
re.assign("transformedTsValueData", new double[]{getSomeDoubles()};
re.eval("estimates <- ugarchfit(spec = garchSpec, data = transformedTsValueData, solver.control = list(trace = 1))");
re.eval("estimates");
The last line returns null. The API documentation says: "the eval method returns null if something went wrong". How do I find out what went wrong?
Granted it's not the most elegant, but you could try getting some information if you put your command in a try catch:
re.eval("estimates <-tryCatch(suppressWarnings(ugarchfit(spec = garchSpec, data = transformedTsValueData, solver.control = list(trace = 1))), error = function(e) { paste(\"e: \",e$message) }, warning = function(w) { paste(\"w: \", w$message) })");
you can then evaluate the response by inspecting the first few 3 characters.
If you don't want to do this for every call, you could repeat your last command if your response is null when you're not expecting it (and repeating something that went wrong usually doesn't take too long).
Edit:
Come to think of it, if the error occurs only when you evaluate "estimates", it may be better to wrap that last one in the try catch:
re.eval("tryCatch(suppressWarnings(estimates), error = function(e) { paste(\"e: \",e$message) }, warning = function(w) { paste(\"w: \", w$message) })");
So I am running the debugger and came across a variable 'e' which I think is error. But within that variable e is a variable "detailMessage". What is the code to get that string displayed?
I would like something along these lines
System.out.println("The error is " + e.detailMessage );
e is e MySQLSyntaxErrorException (id=67)
Where e.detailMessage is the string.
Thanks
The method is
e.getMessage();
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getMessage()
From the Java 7 API (http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html) the method you want is getMessage().
System.out.println("The error is " + e.getMessage());
The correct way to show exceptions is by using a Logger, but for simplicity's sake, you should probably use e.printStackTrace(), this shows you the error as well as the stack where it occured. If you really want just the message (which in itself is not usually very useful) use getMessage()
try{
// ... do something ...
} catch (Exception e){
e.printStackTrace();
}
The method you are looking for is getMessage.
In code:
System.out.println("The error is " + e.getMessage());