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:

JavaScript

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

JavaScript

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.

JavaScript

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

JavaScript
Advertisement