Skip to content
Advertisement

Can you change the Type of Java Exception’s error message?

I’m writing an Internal-Facing tool with a very slow runtime. Because of this runtime I’m trying to validate the input for errors and send a JSON object with a detailed list of every missing or failing element to the client before actually running the tool.

I was wondering if there was a way to modify java Exception’s error message return type so that I can throw this HashMap within an error.

The hashmap containing the errors would look something like this:

Error: {
   Message: "Your X is configured improperly, please fill out the required fields before running this tool", 
   formXErrors: {
     Message: "The following fields are missing from formX", 
     Error: {
       field1Name: "field 1", 
       field2Name: "field 2",
       ... 
    },
    formYErrors: {
     Message: "The following fields are missing from formY", 
     Error: {
       field1Name: "field 1", 
       field2Name: "field 2",
       ... 
     }
  } 
}

And then if an error was found I would like to throw it like this (passing a HashMap into the message field instead of a string):

if (errorHashMap != null) {
  throw new ToolXException(errorHashMap);
}

Java is slightly new to me so I was wondering if anyone could point me towards finding a way to achieve this behavior. Is it even possible? Or is the only way to return this HashMap instead of throwing, and send it to the client?

Thanks in advance!

Advertisement

Answer

You can’t edit the type of a message, but you can certainly add a field of any type you like to a custom Exception type.

class ToolXException extends Exception {
  private final Map<Key, Value> map;
  public Map<Key, Value> getMap() { return map; }
  public ToolXException(Map<Key, Value> map) {
    this.map = map;
  }
} 

…and then you can get it out and display it however you like when you catch it:

try {
  ...
} catch (ToolXException e) {
  doSomethingWith(e.getMap());
}
Advertisement