I updated my code:
1) I added the following properties:
Properties props=new Properties();
props.put(smtp,host);
props.put("mail.smtp.reportsuccess","true");
props.put("mail.smtp.sendpartial", "true");
Then written this block as directed in answer:
}catch (MessagingException mex){
Exception ex = mex;
do {
if(ex instanceof SendFailedException) {
SendFailedException sfe = (SendFailedException) ex;
Address[] vsa = sfe.getValidSentAddresses();
Address[] vua = sfe.getValidUnsentAddresses();
Address[] ia = sfe.getInvalidAddresses();
if(vsa !=null || vsa.length>0){
String validSentAddresses = vsa[0].toString();
printReport("GSWvalidSentAddresses.txt", validSentAddresses);
}
else if(vua !=null || vua.length>0){
String validUnsentAddresses = vua[0].toString();
printReport("GSWvalidUnsentAddresses.txt", validUnsentAddresses);
}
else if(ia !=null || ia.length>0){
String invalidAddresses = ia[0].toString();
printReport("GSWinvalidAddresses.txt", invalidAddresses);
}
else{}
if (ex instanceof MessagingException)
ex = ((MessagingException) ex).getNextException();
else
ex = null;
}//
} while (ex != null);
}//main catch block
}
when it ran throws 504 Gateway Time-out--------nginx
Please advise
Thanks in anticipation
Set the mail.smtp.reportsuccess session property to true. This will cause Transport.send to always throw SendFailedException. Per the documentation:
When sending a message, detailed information on each address that fails is available in an SMTPAddressFailedException chained off the top level SendFailedException that is thrown. In addition, if the mail.smtp.reportsuccess property is set, an SMTPAddressSucceededException will be included in the list for each address that is successful. Note that this will cause a top level SendFailedException to be thrown even though the send was successful.
The use of the word 'chained' means you have to call MessagingException.getNextException().
Also of interest is to you is the 'mail.smtp.sendpartial' property which is also covered in the documentation.
You should also change the code to use Session.getInstance.
Related
There is a method which can:
throw an error
return null
I need to throw a user friendly exception to upper level in the both cases. What is the most elegant way for it? The brute force is:
try {
result = callMethod();
} catch (SomeException e) {
throw new UserFiendlyException("cannot process you, try again pls");
}
if (result == null) {
throw new UserFiendlyException("cannot process you, try again pls");
}
UPD 1: kotlin is accepted and preferable (but I'm also curious how could it be in Java)
UPD 2: Please, don't suggest the use of exceptions for control flow is an anti-pattern: https://softwareengineering.stackexchange.com/questions/189222/are-exceptions-as-control-flow-considered-a-serious-antipattern-if-so-why
If callMethod() is your own method, you could update that to perform the null check internally and throw the error...
function callMethod() {
const responseFromService = null;
if (responseFromService == null)
throw new SomeException(`Expected a valid response from the service but got null.`);
}
try {
result = callMethod();
}
catch (SomeException e) {
throw new UserFiendlyException("cannot process you, try again pls");
}
You can also try the null coalescing operator...
try {
result = callMethod() ?: throw new SomeException(`Escape!`);
}
catch (SomeException e) {
throw new UserFiendlyException("cannot process you, try again pls");
}
Or just keep it simple and check for null within the try...
try {
result = callMethod();
if (result == null) throw new SomeException(`Escape!`);
}
catch (SomeException e) {
throw new UserFiendlyException("cannot process you, try again pls");
}
Edit: Answer originally had the nullish coalescing operator as an option, but the question is for Java, not JavaScript. My bad.
Edit (2): Turns out there is a nullish coalescing operator in Kotlin; option restored.
try...catch and throw are expressions in Kotlin, so you can do:
val result =
try {
callMethod()
} catch (e: SomeException) {
null
} ?: throw UserFiendlyException("cannot process you, try again pls")
The try...catch will produce null if either callMethod returns null. or if an exception occurred. We check if it is null using ?:, and if it is, we throw the user friendly exception.
result will end up having a non nullable type.
I have the following code running in my project:
HashMap<String, DeviceData> deviceMap = getAllDevices();
int status = 0;
DeviceHandle devHandle = null;
for (LicenseData licenseData:listLicenses) {
Map<String, String> licenseMap = licenseData.getLicenseKeyValues();
if ((licenseMap != null && !licenseMap.isEmpty())) {
String keyDecrypt = licenseMap.get("key");
Date expiryDate = new Date(Long.parseLong(licenseMap.get("expiryDate")));
boolean allowForeign = Boolean.parseBoolean(licenseMap.get("allowForeign"));
String ipDecrypt = licenseMap.get("ipAddress");
if (expiryDate.compareTo(new Date()) > 0 || keyDecrypt.equals(licenseData.getKey().getCurrentValueAsString()))
{
try {
DeviceData device = deviceMap.get(ipDecrypt);
devHandle = (DeviceHandle)device.getHandle();
if(device != null && devHandle != null) {
deviceMap.remove(ipDecrypt, device);
System.out.println("After deletion device map.");
System.out.println(deviceMap);
createUser(devHandle);
try {
if (allowForeign) {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statemnt
deleteUser(devHandle);
}
else {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statement
deleteUser(devHandle);
}
} catch(Exception e) {
//Exception statement
deleteUser(devHandle);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Explanation: I have a list of licenses for my application in listLicenses. All the devices present in the server are in deviceMap. For each license, I am decrypting it and getting the values. If license for a device is present, I get a handle on that device and doing some operations.
The issue is:
If I am not able to get a handle on device(getHandle()), or if I am not able to create a user after getting the device handle(createUser()), an exception is thrown. These methods are very hierarchical, i.e I am calling them from here, they are in another class throwing own exceptions and for their operation, they call other methods.
If there are three devices in the map, and three licenses, and if for the first one I am not able to get a handle or create a user, device is removed from deviceMap but no further execution happens i.e. for the next two devices.
If exception occurs for on device, I want to continue the exception for other two devices. I tried using return but couldn't get it to work.
Please help.Also, please forgive for the syntax and if any mismatch is there in the code.
Make use of first try's catch block.
This is how I handled when I faced same kind of situation.
catch (Exception exp) {
if (exp instanceof NullPointerException) {
log.info"Invalid/ Inactive ");
} else if (exp instanceof NonUniqueResultException) {
log.info("Multiple records existed");
} else {
exp.printStackTrace();
errorMsgs.append("Unexpected Error Occured. Please contact Admin.");
}
}
We have a lot of FTL code that performs hash concatenation like this:
<#local event_data = event_data + {
'subaction_name': subactionName
} />
However, these constructs cause some overhead due to the following code (the freemarker.core.AddConcatExpression class’ _getAsTemplateModel(Environment env) method):
try {
String s1 = getStringValue(leftModel, left, env);
if(s1 == null) s1 = "null";
String s2 = getStringValue(rightModel, right, env);
if(s2 == null) s2 = "null";
return new SimpleScalar(s1.concat(s2));
} catch (NonStringException e) {
if (leftModel instanceof TemplateHashModel && rightModel instanceof TemplateHashModel) {
if (leftModel instanceof TemplateHashModelEx && rightModel instanceof TemplateHashModelEx) {
TemplateHashModelEx leftModelEx = (TemplateHashModelEx)leftModel;
TemplateHashModelEx rightModelEx = (TemplateHashModelEx)rightModel;
if (leftModelEx.size() == 0) {
return rightModelEx;
} else if (rightModelEx.size() == 0) {
return leftModelEx;
} else {
return new ConcatenatedHashEx(leftModelEx, rightModelEx);
}
} else {
return new ConcatenatedHash((TemplateHashModel)leftModel,
(TemplateHashModel)rightModel);
}
} else {
throw e;
}
}
because the getStringValue method throws NonStringExceptions in such cases. The NonStringException, in its turn, inherits the following constructor logic from the TemplateException:
super(getDescription(description, cause));
causeException = cause;
this.env = env;
if(env != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
env.outputInstructionStack(pw);
pw.flush();
ftlInstructionStack = sw.toString();
}
else
{
ftlInstructionStack = "";
}
which fetches a full instruction stack each time regardless further handling.
This leads to up to 50 ms of execution time spent on the exception constructors per page request in our case, which is quite critical for the overall throughput.
Could anyone give some advices on how to avoid these exceptions without touching the FTL code, please? Or, maybe, it’s possible to get some kind of a patch, which would move the TemplateModelHash instanceof check before the catch block in the AddConcatExpression._getAsTemplateModel method?
EDIT:
freemarker version 2.3.19
Try to use the latest stable FreeMarker release (2.3.25 at the moment), and see if the speed will be acceptable. A commit in 2013-06-13 says:
This reduces TemplateException creation resource usage further (as far
as it will be silently handled), as the final message from the blamed
expression, tips and so on is only assembled when the message is
indeed needed.
2.3.19 was released earlier than that, on 2012-02-29.
Update: I have committed into 2.3.26-nightly so that falling back to hash addition doesn't rely on exception throwing/catching at all. Not sure how dominant this was in your performance problem, but it was inefficient for sure.
I have a Java method like below:
private boolean getBooleanProperty(String property, String defaultValue) {
boolean result = false;
try {
result = Boolean.parseBoolean(properties.getProperty(property, defaultValue));
} catch (IllegalArgumentException | NullPointerException e) {
}
return result;
}
I know that the way I am handling the exceptions in above method is not correct and looking for the way to have those more aligned with the Java standards and best practices.
Similarly for the method below:
public void getStatusAndAnnotation(ITestResult result) {
try {
HashMap<Object, Object> map = new HashMap<>();
Method method = result.getMethod().getConstructorOrMethod().getMethod();
TestInfo annotation = method.getAnnotation(TestInfo.class);
try {
//add id removing the first character of the annotation (e.g. for C12034, send 12034)
if(annotation!=null) {
map.put("id",annotation.id().substring(1));
}
}catch (NullPointerException e){
e.printStackTrace();
}
if (result.getStatus() == ITestResult.SUCCESS) {
map.put("result", 1);
} else if (result.getStatus() == ITestResult.FAILURE) {
map.put("result", 9);
} else if (result.getStatus() == ITestResult.SKIP) {
map.put("result", 10);
}
if (annotation != null) {
if(annotation.trDeploy() && !map.get("id").equals(null) && !map.get("id").toString().isEmpty())
{
ApiIntegration.addTestResult(map);
}
else System.out.println("Deploying result was canceled, because test has annotation \"trDeploy: false\" or \"id\" has no value");
}
} catch (SecurityException | IOException
| ApiException | NullPointerException e) {
e.printStackTrace();
}
}
How do I handle these different exceptions to align with the best practices?
What I typically do is let the compiler/IDE tell me what exceptions I need to catch unless you want to catch an exception for a specific reason. That way, I can code without catching unnecessary exceptions and my code is cleaner.
These type of Exceptions are called Checked Exceptions
"In the Java class hierarchy, an exception is a checked exception if
it inherits from java.lang.Exception, but not from
java.lang.RuntimeException. All the application or business logic
exceptions should be checked exceptions."
Example:
try
{
// open a file (Compiler will force to either catch or throw)
}
catch (IOException ioe)
{
ioe.printStackTrace();
// need to make a decision on what to do here
// log it, wrap it in a RuntimeException, etc.
}
As for Unchecked Exceptions
"Unchecked, uncaught or runtime exceptions are exceptions that can be
thrown without being caught or declared"
Example:
String x = null;
// this will throw a NullPointerException
// However, you don't need to catch it as stated in some the comments
x.toString();
What you should do is prevent it
if (x == null)
{
x = "some default value"; // prevent the exception from happening.
}
x.toString();
Does this mean you should never catch a RuntimeException
No, of course not. It depends on the scenario.
Take this example:
String number = "12345";
// You don't know if number is a valid integer until you parse it
// If the string is not a valid number, then this code will
// throw an Exception
int i = Integer.parseInt(number);
Instead you can catch a NumberFormatException. Again, this is a form of prevention.
int i = 0; // some default
try
{
i = Integer.parseInt(number);
}
catch (NumberFormatException nfe)
{
// Good practice to log this, but the default int is fine.
}
Some Best Practices
Do not catch exceptions unless the compiler forces you to.
If you are catching a checked exception, then log it. You can also wrap it in a RuntimeException if you want it to percolate up the call stack.
If you want to catch a RuntimeException, then do so with a purpose (i.e. you can set a default and prevent the error all together.)
Don't have a chain of methods all throwing a checked Exception up the stack trace. This is very messing and forces all calling methods to either catch or throw the checked exception.
Catching a RuntimeException just to log it really doesn't have much of a purpose. Unless you are logging it in a catch all location.
Catch-All Example:
try
{
// entry point to application
}
catch (Throwable t)
{
// let all exceptions come here to log them
}
I am getting nullpointerexception, don't know what actually is causing it. I read from java docs that fileinputstream only throws securityexception so don't understand why this exception pops up.
here is my code snippet.
private Properties prop = new Properties();
private String settings_file_name = "settings.properties";
private String settings_dir = "\\.autograder\\";
public Properties get_settings() {
String path = this.get_settings_directory();
System.out.println(path + this.settings_dir + this.settings_file_name);
if (this.settings_exist(path)) {
try {
FileInputStream in = new FileInputStream(path + this.settings_dir + this.settings_file_name);
this.prop.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
this.create_settings_file(path);
try{
this.prop.load(new FileInputStream(path + this.settings_dir + this.settings_file_name));
}catch (IOException ex){
//ex.printStackTrace();
}
}
return this.prop;
}
private String get_settings_directory() {
String user_home = System.getProperty("user.home");
if (user_home == null) {
throw new IllegalStateException("user.home==null");
}
return user_home;
}
and here is my stacktrace:
C:\Users\mohamed\.autograder\settings.properties
Exception in thread "main" java.lang.NullPointerException
at autograder.Settings.get_settings(Settings.java:41)
at autograder.Application.start(Application.java:20)
at autograder.Main.main(Main.java:19)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Line 41 is: this.prop.load(in);
If line 41 is this.prop.load(in); then it seems as though this.prop == null
Add a breakpoint on the line to verify.
Attempting to call a method on a null instance results in a NullPointerException.
Is the variable prop null when it is executing on line 41? Try debugging your program to check this. e.g. add
if(prop == null)
System.out.println("prop is null");
Also, NullPointerException is an unchecked exception so isn't documented in Javadoc.
I think the other reviewers did a fair job in explaining your problem.
Couple of pointers:
I noticed that you are catching certain exceptions but not throwing them. If you do not throw the exception then there is no point in catching them.
Secondly, to avoid NPEs you should always check if any of your object is null before executing anything on the object.