Tuesday, September 28, 2021

Wednesday, September 22, 2021

Java learnings - Handling bad request

Consider you have a records array 
and 
each record has to be validated independently in your service 
And
In json response , you want to respond status of each record.

This can be achieved by Overriding above function in your global exception hander. 

Sample use case :

'Records" : [
       {
           "name" : "name",
           "Id": 123
        },
      {
           "name" : "name2",
           "Id": 124
        },
    {
           "name" : "name",
           "Id": 123x
        },
}

And 
You wrote Jason property validation on "Id" where it can't accept non integer.

Then you can annotate
--------
@jsonproperty("id')
@PositiveOrZero(message = "incorrect Id")
Private Integer Id:
--------

Because of above annotation, framework will raise a exception which will call the abobe overrided funcion. Here we will be able to do.


'Cause" : [
       {
           "Messsage" : "incorrect id",
           "Field": "records[2].I'd"
        },
     
}

Ref: https://www.journaldev.com/1696/exception-handling-in-java
https://www.javadevjournal.com/spring/exception-handling-for-rest-with-spring/