java - Spring controller throwing HttpStatus.UNAUTHORIZED fires 500 Http error instead of 401 -
here's scenario : created following custom response exception, fire 401 http status :
@responsestatus(value = httpstatus.unauthorized) public class httpunauthorizedexception extends runtimeexception { }
the controller uses exception :
@controller public usercontroller { @requestmapping(value = "api/user") @responsebody public string dologin( @requestparam(value = "username", required = false) string username, @requestparam(value = "password", required = false) string password) { if(userloggedin(string username, string password)) { return "ok"; } else { throw new httpunauthorizedexception(); } } ... }
now when try access controller see 401 exception, server fires http error code 500 instead. interestingly enough, when try httpstatus.not_found
works, server fires 404. there i'm missing on here?
thanks in advance :-)
first throw new httpunauthorizedexception();
then can catch @ normal controller have @controlleradvice
annotation
@controlleradvice // handle exceptions public class exceptioncontroller { //// ........... @exceptionhandler({httpunauthorizedexception.class}) @responsebody @responsestatus(value = httpstatus.unauthorized) map<string, string> unauthorizedaccess(exception e) { map<string, string> exception = new hashmap<string, string>(); log.error("unauthorized access api: " + e.getmessage(), e); exception.put("code", "401"); exception.put("reason", e.getmessage()); return exception; } }
Comments
Post a Comment