Java SpringREST控制器异常处理
如何配置单个rest控制器来处理返回不同对象类型的不同API调用的异常Java SpringREST控制器异常处理,java,spring,rest,spring-mvc,exception-handling,Java,Spring,Rest,Spring Mvc,Exception Handling,如何配置单个rest控制器来处理返回不同对象类型的不同API调用的异常 @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Foo> method1() @RequestMapping(method = RequestMethod.GET) public ResponseEntity<Bar> method2() @RequestMapping(method=RequestMethod.
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Foo> method1()
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Bar> method2()
@RequestMapping(method=RequestMethod.GET)
公共响应方法1()
@RequestMapping(method=RequestMethod.GET)
公共响应方法2()
假设method1()和method2()都抛出MyException的一个实例,那么我需要以以下方式对它们进行不同的处理:
@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseEntity<Foo> handleFoo(Exception ex) {
//Return foo with error description
Foo f = new Foo();
f.setError(ex.getMessage());
//Set f to response entity
return new ResponseEntity<>();
}
@ExceptionHandler(MyException.class)
@ResponseBody
public ResponseEntity<Bar> handleBar(Exception ex) {
//Return bar with error description
Bar b = new Bar();
b.setError(ex.getMessage());
//Set b to response entity
return new ResponseEntity<>();
}
@ExceptionHandler(MyException.class)
@应答器
公共响应handleFoo(例外情况除外){
//返回带有错误描述的foo
Foo f=新的Foo();
f、 setError(例如getMessage());
//将f设置为响应实体
返回新的ResponseEntity();
}
@ExceptionHandler(MyException.class)
@应答器
公共响应把手(例外情况除外){
//带有错误描述的返回条
杆b=新杆();
b、 setError(例如getMessage());
//将b设置为响应实体
返回新的ResponseEntity();
}
当method1()抛出MyException实例时,应调用handleFoo()。
对于method2(),应该调用handleBar()
这在单个Rest控制器中是可能的,还是每个方法需要两个Rest控制器?ExceptionHandler的优点是,您可以在一个位置处理来自多个位置的相同异常。您正在寻找相反的方法:在多个位置/方式中处理异常
您无法在单个类和注释中实现这一点,但您可以在
method1()
和method2()
中使用正常的try/catch
来实现这一点。在异常情况下,您不必返回ResponseEntity
或ResponseEntity
。您可以创建一个错误实体并像ResponseEntity一样返回它。否则,在每个场景中引发两个不同的异常,这是不可能的。我尝试向现有控制器添加一个新方法(比如method2()),并对其使用相同的异常处理逻辑。我同意你所说的。