Get a custom error message, instead of 500 - java

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.

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

HttpServerErrorException.InternalServerError does not catch the Error 500 from the Http Request Resttemplate

I am currently working on a service that hit another service from another team, which gives the response code 500 when the service has no data to be sent. At first, I can utilize the HttpServerErrorException.InternalServerError to catch the exception and get the response body. However, this did not work as it used to. That error was not caught by that Exception and when I tried using catch (Exception e), it also caught nothing and let it through that makes the service not running correctly..
Below is the code, what is actually wrong from my code below? How should I handle that 500 response code?
Map resultMap1;
try {
resultMap1 = restTemplate.postForEntity(url, request, Map.class);
} catch (HttpServerErrorException.InternalServerError e) {
resultMap1 = new HashMap();
resultMap1.put("errorMessage", e.getMessage());
return resultMap1;
} catch (HttpServerErrorException.GatewayTimeout e) {
throw new AppException(
GATEWAY_TIMEOUT_CD,
GATEWAY_TIMEOUT_MSG +": "+ url,
null
);
} catch (HttpServerErrorException.BadGateway e) {
throw new AppException(
BAD_GATEWAY_CD,
BAD_GATEWAY_MSG +": "+ url,
null
);
} catch (HttpServerErrorException.ServiceUnavailable e) {
throw new AppException(
SERVICE_UNAVAILABLE_CD,
"The service "+ url +" was unavailable.",
null
);
}
Map returnMap = new HashMap(); // this is to be the result from my service
switch (resultMap.get("content_type")){ // In this one, I get NullPointerException
// Here would be selection how the content should be treated, different content have different treatment
}
I know that the NullPointerException can actually be handled by adding ELSE or another case, However, I curious about why the Exception wasn't caught well as it supposed to be.

Android - Parsing a JSON string

I'm trying to parse a simple JSON string
try {
String candyJson = "{\"candies\":[ {\"name\":\"Jelly Beans\", \"count\":10}, {\"name\":\"Butterscotch\", \"count\":6}]}";
JSONObject candiesJSONobject = new JSONObject(candyJson);
JSONArray candiesJSONarray = candiesJSONobject.getJSONArray("candies");
Log.v("JSONObject", candiesJSONarray.getJSONObject(0).getString("name"));
} catch (JSONException e){
Log.e("MYAPP", e.toString());
}
The code works fine in this state without catching any exception and prints JSONObject name in the Android Log.
However when I don't try to catch the exception as shown in the following example:
String candyJson = "{\"candies\":[ {\"name\":\"Jelly Beans\", \"count\":10}, {\"name\":\"Butterscotch\", \"count\":6}]}";
JSONObject candiesJSONobject = new JSONObject(candyJson);
JSONArray candiesJSONarray = candiesJSONobject.getJSONArray("candies");
Log.v("JSONObject", candiesJSONarray.getJSONObject(0).getString("name"));
Android Studio gives me unhandled exception error on all JSON methods. Is it necessary to catch JSONException when parsing a JSON or am I doing something wrong?
This is a Java feature actually :-) Please read more about it here.
The idea is that - if a method states that it will throw an (non-Runtime) Exception, all the calls of that method are required to catch this exception, just in case.
It does not mean that you are getting this exception in your code, you can only see that when you actually run it. But Java requires you to be prepared for a situation where such exception is thrown.
Well since you're working with the org.json... json objects, yes most of their methods do throw exceptions that you must catch and handle.
However if you don't want to handle each exception on it's own i suggest you create a json utils class that will handle those things for you.
For example for the JSONObject constructor you can make your own method like so
public static JSONObject createObjectFromString(String objectString) {
try {
return new JSONObject(objectString);
} catch (JSONException e) {
Log.e("MYAPP", e.toString());
}
}
and just reuse this method when you want to create a new json object.
Yes actually if any method is throwing Exception you need to catch that Exception.
This is called as Checked Exceptions or Compile Time Exceptions.
In your case methods like
JsonArray getJsonArray(String name)
or
JsonObject getJsonObject(String name)
check here http://docs.oracle.com/javaee/7/api/javax/json/JsonObject.html#getJsonArray-java.lang.String-
are throwing ClassCastException So you either catch it or throw the exception.
Throwing Exception will lead to crash the app, So better Catch it.
If any method throws checked Exception, then caller can either handle this exception by catching it or can re throw it by declaring another throws clause in method declaration.
This is the reason Android Studio is showing unhandled exception error.

unhandled exception org.json.jsonexception

I'm working on an android app, and the app must save a java object in json format into the SQLite database. I wrote the code for this operation, then they must extract the Json object and reconvert it into a Java Object.
When I try to call the method for deserializing the json object in to a string, I found this error in Android Studio:unhandled exception org.json.jsonexception
When I try to catch JSONException e the program runs but don't deserialize the json object.
This is the code for the method:
private void read() throws JSONException {
SQLiteDatabase db = mMioDbHelper.getWritableDatabase();
String[] columns = {"StringaAll"};
Cursor c = db.query("Alle", columns, null, null, null, null,null );
while(c.moveToNext()) {
String stringaRis = c.getString(0);
JSONObject jObj = new JSONObject(stringaRis);
String sPassoMed = jObj.getString("passoMed");
final TextView tView = (TextView) this.findViewById(R.id.mainProvaQuery);
tView.setText(sPassoMed);
// }
}
}
Can you help me please?
Yes, you need to catch the exception.
But when you catch it, you should not just throw it on the floor. Your application needs to do something about the exception. Or if you / it is not expecting an exception to occur at runtime, then at least you should report it. Here's a minimal example (for an Android app)
try {
...
JSONObject jObj = new JSONObject(stringaRis);
...
} catch (JSONException e) {
Log.e("MYAPP", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
Of course, this does not solve your problem. The next thing you need to do is to figure out why you are getting the exception. Start by reading the exception message that you have logged to logcat.
Re this exception message:
org.json.JSONException: Value A of type java.lang.String cannot be converted to JSONObject
I assume it is thrown by this line:
JSONObject jObj = new JSONObject(stringaRis);
I think that it is telling you is that stringaRis has the value "A" ... and that cannot be parsed as a JSON object. It isn't JSON at all.

Multiple catch statements with the same exception types

I've been looking all over for an answer to this and have yet to find one.
Basically I am trying to connect to a database server through a GUI. My boss wants to be able to enter all fields and then check to see if they are valid entries, then if there are any invalid entries, he wants me to turn the text red, indicating that the field is invalid. I have the try statement catch ClassNotFoundException and SQLException. Because there are multiple fields that need to be checked, I have tried to have a set of if statements to check the connection info. Here is the code below, I hope this makes sense...
//The cancel boolean values in this code are used elsewhere to regulate the Threads
try
{
//attempt connection here
}
catch(ClassNotFoundException | SQLException e)
{
String[] errors = new String[4]; //This will create a String array of the errors it catches
//and will later get called into a method that displays
//the messages in a JOptionPane.showMessageDialog()
if (e.getMessage().startsWith("The TCP/IP connection to the host"))
{
errors[0] = "SQL CONNECTION FAILED: Please check the server URL you entered to make sure it is correct.";
cancel = true;
mGUI.serverNameTextField.setForeground(Color.RED);
}
if (e.getMessage().startsWith("Login failed for user"))
{
errors[1] = "LOGIN FAILED: You do not have sufficient access to the server.";
cancel = true;
}
if (e.getMessage().startsWith("Cannot open database"))
{
errors[2] = "SQL CONNECTION FAILED: Please check the database name you entered to make sure it is correct.";
cancel = true;
mGUI.dbNameTextField.setForeground(Color.RED);
}
mGUI.reportErrors(errors); //Method where it reports the String[] array of errors
//However, the 'errors' parameter only returns one error
//message at a time, which is the problem.
Thanks for any help!
****EDIT******
I found a solution, so hopefully this will help someone. I changed my if statements to add an AND argument checking for the specific error code. You find find the error code by either setting a break point and looking at the debug perspective, or you can do what I did and set a print statement to see the error code. Here is the print statement:
System.out.println(((SQLException) e).getErrorCode());
Here are my new for statements:
try
{
//attempt connection here
}
catch(SQLException | ClassNotFoundException e)
{
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 0)
{
//code here
}
else{
//code here
}
System.out.println(((SQLException) e).getErrorCode()); //Here is the print statement to see the error code.
if (e instanceof SQLServerException && ((SQLServerException) e).getErrorCode() == 4060)
{
//code here
}else{
//code here
}
if(cancel != true)
{
//code here
}
}
You can do it in multiple ways
1 having more than one catch with a common function
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
where handleError takes the exception as the argument.
You dont seem to do anything else so you can just combine them both into a single exception
}catch(Exception e){
}
which will catch everything but you have MUCH less control over the error handling.
A general principle of exceptions is that they are handled at the point they are best abled to be handled.
You seem to have very disparate exceptions and presumably a TCP exception thrown somewhere in the code is not the same as the SQLException thrown when connecting to a database (I might be wrong here since I don't know what the rest of the code looks like). So would not a set of exception handlers, one for each type make more sense. Also to reite from Bryan Roach, text disambiguation is not a good idea.
try {
...
} catch (java.net.SocketException e) {
e[0] = "tcp error";
} catch (java.sql.SQLException e) {
e[1] = "sql exception happened";
}
Also your string array seems a bit risk, possibly a
ArrayList errors = new ArrayList();
errors.add("Some tcp error");
errors.add("Some db error");
and then for you error reporting
mGUI.reportErrors(errors.toArray())
would preserve your interface and not waste you having to allocate extra elements to the array and have empty entries. I don't know exactly what your question is, but you allude to the GUI not displaying multiple errors. Possibly there is a check which stops at the first empty element in an array. Say e[2] and e[4] is populated, it might stop when it iterates over the errors as e[3] is empty. I'm presuming again since I don't know what that code looks like
From the comments above it sounds like what you want to do is have different logic for the various Exception types you are catching within a single catch block. If this is the case, you could go:
...
catch(ClassNotFoundException | SQLException e) {
String[] errors = new String[4];
if (e instanceof ClassNotFoundException) {
//do something here
}
if (e instanceof SQLException) {
//do something else here
}
...etc
}
This should work, but it's probably just as easy to use multiple catch blocks as others have suggested:
}catch (ClassNotFoundException e){
handleError(e);
}catch (SQLException e){
handleError(e);
}
I don't mean any offense, but the way the code handles exceptions might cause some headaches down the road. For example:
if (e.getMessage().startsWith("Cannot open database")) {
Here the code relies on the supporting library that throws the exception to use the same text description, but this description might change if you switch to another JVM version, use a different database driver, etc. It might be safer to go by the exception type, rather than the exception description.

Try catch exception (letter in int)

I'm trying to use a try catch structure to show an error when I try to input a letter into a string. Which exception should I be using for this? the console shows me InputMismatchException but this does not work.
input that works:
beginnen = 1
input that doesn't work:
beginnen = a
it obviously doesn't work cause i'm putting a string into an int, I just want to have a message show up when this occurs
int beginnen;
String error = "Something went wrong";
try {
beginnen = Input.readInt();
}
catch (InputMismatchException IME) {
System.out.println(error);
}
error that shows up:
Exception in thread "main" java.util.InputMismatchException
If the documentation is foggy, use experiment:
try {
beginnen = Input.readInt();
} catch (Throwable x) {
System.err.println("Catched "+x.getClass().getName());
}
This will print the exact class name for you and you can later change your code to catch the exception of this class. This will also show for you, maybe just nothing is actually thrown.
Your Try/Catch expression looks fine to me, however you've mistakenly referenced error, which is not defined anywhere.
Try changing it to System.out.println(IME.getMessage());

Categories

Resources