Home > front end >  Get a custom error message, instead of 500
Get a custom error message, instead of 500

Time:09-21

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.

CodePudding user response:

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.

  • Related