Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get a custom error message, instead of 500

I have a service that looks like this:

public String storeTestRequest(Map<String, String> data, HttpSession session) {
    JSONObject json = new JSONObject(data);

    boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true");

    try {
        this.testRequestRepository.save(new TestRequest(
                json.getAsString("firstname"),
                json.getAsString("surname"),
                json.getAsString("street"),
                hasHealthInsurance             
        ));
        return "All good.";
    }
    catch (Exception e) {
        return "Something went wrong.";
    }
}

In this example, I am saving the values of 4 fields but in fact there are much more and I don’t want to validate any of them. So if all values could be saved successfully, I should get the message All good. But if some values are missing, I should get the message Something went wrong..

I have tried it with try & catch but I still get a 500 error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your hasHealthInsurance property is empty or null. Your exception message says it’s caused by this line.

boolean hasHealthInsurance = json.getAsString("hasHealthInsurance").equals("true");

If you put this line in your try catch block, you will see the exception message in the catch block.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading