Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get path variable out of HttpMessageNotReadable exception

We have some web services which are being consumed by mobile clients , in which the mobile clients make some request's and we return response to them. Somehow if the client make any invalid request we throw Custom Exceptions .
But recently the mobile client has made some request which was out of range for Long variable.
The client has different variables for ex ::

    {
      "accountId":"343"
      "Amount":"90909090909090909090"
    }

In case of the value for accountId or Amount are made more than 19 digits we get HttpMessageNotReadable exception as the range is out of long value. But from exception i am not able to fetch for which variable the exception has been raised whether for accountId or Amount. From the exception i am getting this information in _path variable but i am not able to fetch it. enter image description here

And in the path variable i get something like::

[com.Upload["AccountInfo"], com.Info["Account"]]

Does somebody know how to fetch this information.

like image 811
Anand Kadhi Avatar asked Jan 28 '16 05:01

Anand Kadhi


2 Answers

The following code prints out the field which causes the exception.

InvalidFormatException invalidFormatException = (InvalidFormatException) exception
        .getCause();
System.out.println(invalidFormatException.getPath().get(0)
        .getFieldName());
like image 81
ArunM Avatar answered Nov 19 '22 20:11

ArunM


@ArunM's answer works as long as the field is in 1st level viz the example given by OP.

But what happens when the field is in nested json? say paymentType has wrong value in the following example?

{
  "userType": "CUSTOMER",
  "payment": {
                 "amount": 123456,
                 "paymentType": "INTERNET_BANKING"
              }
}

In the above example, if there's anything wrong with the value of userType, there will be just one element in _path.

But if any value inside the payment is wrong, say for example paymentType, there will be multiple elements in the _path variable. Each element representing the hierarchical attribute.

So for paymentType, _path will have 2 elements as illustrated below:

_path[0].fieldName = "payment"
_path[1].fieldName = "paymentType"

Hence the correct approach is to get the last element in _path as shown below. If needed, we can build the complete path by using all the elements.

InvalidFormatException ifx = (InvalidFormatException) exception.getCause();
System.out.println(ifx.getPath().get(ifx.size() - 1).getFieldName());

This I believe is the right approach to get the invalid attribute name.

like image 44
Arun Gowda Avatar answered Nov 19 '22 20:11

Arun Gowda