validation - Spring Validator and BindingResult - How to set different HttpStatus Codes? -
dear spring community,
i building project using spring. in api layer, leveraging validator interface in order custom validation , set error.
@override public void validate(object obj, errors e) { signuprequest signuprequest = (signuprequest) obj; user user = userservice.getuserbyemail(signuprequest.getemail()); if (user != null) { e.rejectvalue("user", errorcodes.user_exist, "user exist"); } }
now, in api signature, since using bindingresult object, in @controlleradvice have, if user provides empty value attribute of dto object, wont able @exceptionhandler(methodargumentnotvalidexception.class).
what means that, wont able throw httpstatus.bad_request
empty value provided. in above case of validator, wont httpstatus.bad_request
rather httpstatus.ok
. problem that, how provide different httpstatus types based on errors getting validator? there way have empty value still picked @exceptionhandler(methodargumentnotvalidexception.class)
in @controlleradvice
, have other custom validations picked bindingresult?
i hope clear on question. appreciate help!
ok, believe came solution! in order have different httpstatus being thrown base on type of error have, need have custom exceptions. have custom exceptions thrown inside validator. controlleradvice should register pick custom exceptions , act upon them accordingly.
for example validator should have this:
if (!matcher.matches()) { e.rejectvalue("email", errorcodes.email_invalid, "email address invalid"); throw new badrequestexception("email address invalid", e); } user user = userservice.getuserbyemail(signuprequest.getemail()); if (user != null) { e.rejectvalue("email", errorcodes.user_exist, "user exist"); throw new validationexception("user exist", e); }
and controller advice should have:
@exceptionhandler(validationexception.class) @responsebody public responseentity<map<string, object>> handlevalidationexception( validationexception validationexception) { map<string, object> result = createerrorresponse(validationexception.geterrors()); return new responseentity<map<string, object>>(result, httpstatus.ok); } @exceptionhandler(badrequestexception.class) @responsebody public responseentity<map<string, object>> handlebadrequestexception( badrequestexception badrequestexception) { map<string, object> result = createerrorresponse(badrequestexception.geterrors()); return new responseentity<map<string, object>>(result, httpstatus.bad_request); }
this way, can have different httpstatus returned base on type of error have.
Comments
Post a Comment