Link to home
Start Free TrialLog in
Avatar of roy_sanu
roy_sanuFlag for India

asked on

issue on Exception handling

Experts,

is it good to have a ParseException or try catch   which would be much better way handling...

@CrossOrigin
      @RequestMapping(value = "save/", method = RequestMethod.POST, produces = { "application/json" })
      public Map<String, Object> createCounseling(@RequestBody String counselingData) throws Parse{
            JsonObject CounselingObject = Json.parse(counselingData).asObject();
            HibernateDao<Counseling> workerDao = counselingDaoFactory.getNewDao(Counseling.class);
            Counseling counseling = getCounselingObject(CounselingObject);
            Map<String, Object> counseilingMap = new HashMap<>();
            workerDao.save(counseling);
            counseilingMap.put("status", HttpStatus.OK);
            counseilingMap.put("data", new ArrayList<>());
            return counseilingMap;
      }

Thanks
Avatar of ste5an
ste5an
Flag of Germany image

1) Your method does not return what its name promises.
2) The factory method / builder is responsible for creating the object(s) from the request body. They should not be separated over different classes.
3) As the createCounseling() method is the endpoint, you should specify via consumes in the @RequestMapping that you only accept application/json. Then parse errors based on non-JSON data cannot happen
4) The factory method can throw an exception if the JSON contains invalid data or you make it exception free, something like:

@CrossOrigin
@RequestMapping(value = "save/", method = RequestMethod.POST, produces = { "application/json" })
public Map<String, Object> createCounseling(@RequestBody String counselingData) throws Parse{
    Map<String, Object> counseilingMap = new HashMap<>();
    Counseling counseling = Counseling.createCounseling(counselingData);		
    counseilingMap.put("status", counseling != null ? HttpStatus.OK : HttpStatus.BAD_REQUEST);
    if ( counseling != null ) {
        // Success.
        workerDao.save(counseling);
        counseilingMap.put("data", new ArrayList<>());
    } 
	
    return counseilingMap;
}

public static Counseling createCounseling(String counselingData) {
    Counseling result = new Counseling();
    // TODO: parse counselingData into counseling.
    // When an error/exception occurs set result = null.
    return result;
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of gsk
gsk

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial