java - Custom exception handle with spring boot -


here,my requirement want separate code in application exception handling,i saw nice option of spring there using @controller advice handle exceptions globally.

@controlleradvice  class globalcontrollerexceptionhandler {     @responsestatus(httpstatus.conflict)  // 409     @exceptionhandler(dataintegrityviolationexception.class)     public void handleconflict() {         // nothing     } } 

but there want cutomization there,like proper dynamic messages,own error code. how can this,i new spring boot , don't have knowledge of spring.need basic example.

you can come class capture information sent in response in case of exception:-

public class apiresponse  {      int errorcode;      string description;      string someinformation;      // other information want send in case of exception. }   @controlleradvice class globalcontrollerexceptionhandler {     @responsestatus(httpstatus.conflict)  // 409     @responsebody     @exceptionhandler(dataintegrityviolationexception.class)     public apiresponse handleconflict(dataintegrityviolationexception exception) {         apiresponse  response = createresponsefromexception(exception);         return response;     } } 

in controller advice class:-

  1. have return type apiresponse instead of void.
  2. the handler method can have exception raised argument.
  3. using exception object create apiresponse object.
  4. put @responsebody on handler method.

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -