Home > Blockchain >  Can you change the Type of Java Exception's error message?
Can you change the Type of Java Exception's error message?

Time:12-07

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!

CodePudding user response:

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());
}

CodePudding user response:

This is absolutely possible. They way to do it is to create a sub class of one of the throwable subclasses: Exception, RuntimeException, or Error. The other thing you need to think about is whether you want to chain your custom Exception to a caught Exception, or whether it should be independent of a "root cause"

  • Related