java - Spring rest controller exception handling -


how configure single rest controller handle exceptions different api calls returning different object types?

@requestmapping(method = requestmethod.get) public responseentity<foo> method1()   @requestmapping(method = requestmethod.get) public responseentity<bar> method2() 

let's both method1() , method2() throws instance of myexception, need handle them differently following way:

@exceptionhandler(myexception.class) @responsebody public responseentity<foo> handlefoo(exception ex) {     //return foo error description     foo f = new foo();     f.seterror(ex.getmessage());     //set f response entity     return new responseentity<>();  }  @exceptionhandler(myexception.class) @responsebody public responseentity<bar> handlebar(exception ex) {      //return bar error description     bar b = new bar();     b.seterror(ex.getmessage());     //set b response entity     return new responseentity<>();  } 

when method1() throws instance of myexception, handlefoo() should called. , method2(), handlebar() should called.

is possible in single rest controller or need 2 rest controllers each method?

the advantage of @exceptionhandler can have same exception multiple places handled in single place. you're looking opposite: handling exception in multiple places/ways.

you can't achieve within single class , annotation, can normal try/catch in method1() , method2().


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -