如何配置单个休息 Controller 来处理返回不同对象类型的不同 API 调用的异常?
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Foo> method1()
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Bar> method2()
假设 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<>();
}
当method1()抛出MyException实例时,应该调用handleFoo()。 对于method2(),应该调用handleBar()。
这可以在单个 Rest Controller 中实现吗?还是每个方法都需要 2 个 Rest Controller ?
最佳答案
@ExceptionHandler 的优点是您可以在一个地方处理来自多个地方的相同异常。您正在寻找相反的情况:在多个位置/方式处理异常。
您无法在单个类和注释中实现此目的,但您可以使用 method1()
和 中的普通
.try/catch
来实现此目的方法2()
关于java - Spring Rest Controller 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39375697/