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:-
- have return type apiresponse instead of void.
- the handler method can have exception raised argument.
- using exception object create apiresponse object.
- put @responsebody on handler method.
Comments
Post a Comment