views:

58

answers:

3

Hi I have below pseudo code with throws an exception like this

throw new MyException("Bad thing happened","com.stuff.errorCode");

where MyException extends Exception class. Below is how I am handling the exception

 ActionMessages errors = new ActionMessages();
if(ex.getErrorCode() != null && !"".equals(ex.getErrorCode()))
error = new ActionMessage(ex.getErrorCode()); // com.stuff.errorCode is the errorCode
else
error = new ActionMessage(ex.getMessage()); //"Bad thing happened" is error message
errors.add(ActionMessages.GLOBAL_MESSAGE, error);
//errors.add(Globals.MESSAGE_KEY, error );
saveErrors( requ, errors );
return (mapping.findForward(nextScreen));

Now on the user screen the message appears as

???en_US.Bad thing happened???

I am using Struts 1.2.4 and I am looking into the source code of it, but any pointer will be greatly appreciated.

A: 

Java is looking for application resources to contain the localized version of your error message.

That is what the ???en_US??? thing is about. For some reason, it thinks that you are referencing a key "Bad thing happened" and are looking for a localized (i.e. translated) message.

Why?

Not sure yet. Could you post your whole MyException class?

Tim Drisdelle
+2  A: 

Edit: this answer was written before the question was substantially changed.

The "???en_US" thing must come from somewhere else (possibly the web framework you use for printing the message), because Exception itself doesn't do any lookups.

Compile this code:

public class MyException extends Exception {
  public MyException(String msg, String sErrorCode) {
    super(msg);
    // ignore sErrorCode
  }
}

public class MyExceptionTest {
  public static void main(String[] args) {
    System.out.println(new MyException("foo", "bar").getMessage());
  }
}

and run MyExceptionTest and you will see a simple "foo" as the output (as it's expected).

Joachim Sauer
+1 - this is the most likely explanation, IMO.
Stephen C
Yes, it is.I got the wrong flow earlier. I have modified question with correct details.
Ravi Gupta
+1  A: 

To avoid ActionMessage trying to interpret your literal message as a key use this constructor:

error = new ActionMessage(ex.getMessage(), false);

The boolean parameter specifies if the String parameter will be interpreted as a code to be looked up (true) or as a literal message (false).

Joachim Sauer
Assuming by default it is false, it should work fine for error = new ActionMessage(ex.getErrorCode()) where I am having proper message set up in ApplicationResources.properties for this error code ?
Ravi Gupta