开发者

Weird output of Throwable getMessage()

开发者 https://www.devze.com 2022-12-22 22:31 出处:网络
Hi I have below pseudo code with throws an exception like this throw new MyException(\"Bad thing happened\",\"com.stuff.errorCode\");

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

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

where MyException extends Exc开发者_JAVA技巧eption 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.


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).


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).


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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号