java - How can I provide meaningful error feedback from validation without side effects? -


i'm trying figure out clean way manage validation of rest endpoints allow me provide meaningful feadback user in case of error (http status code , error message) while @ same time avoiding side effects in validation methods performing work.

for instance, need parse json object coming in, first need validate parses , object represents it. if exception during parsing want tell user want object validation method if parses correctly.

there 2 concerns here, validation , translating json string pojo. if put them in same method how return error string if parsing fails without having side effect?

super pseudo-code showing 1 possibility, side-effect:

public pet parsepet(httpresponse httpresponse, string petstr) {     pet pet = null;     try {         parser parser = new parser();         pet = parser.parse(petstr, pet.class);     } catch(exception e) {         httpresponse.setstatus(400);     }     return pet; } 

obviously in case use null response determine didn't parse , avoid side-effect, in more complex example different errors produce different error status' how can avoid side effects?

is there standard best practice or architectural concept sort of thing?

the "cleanest" option think of throw new exception validationexception(int statuscode) thrown when business rule broken. whole "exceptions exceptional things" comes play. given i'm returning error user, seems exception acceptable here though.

if put them in same method how return error string if parsing fails without having side effect?

throw exception when error happens. higher interpret , convert http error response.

something else comes haskell world have method return either<pet, error>. 1 of these 2 (pet or error) filled in. caller needs figure out one. i'm giving option here, not i've seen in idiomatic java code.

the "cleanest" option think of throw new exception validationexception(int statuscode)

i think smidgen cleaner throw petparsingexception , higher interprets exception , decides it's 400. validation doesn't have know it's part of restful api.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -