java - Spring Rest Controller 异常处理

标签 java spring rest spring-mvc exception

如何配置单个休息 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/

相关文章:

java - 将文本设置为变量

java - 两种方法之间 IO 速度的意外巨大差异

Java:我的编译器说我的 printf 语句之一已损坏,我不明白为什么

java - 在 Akka 中对一对外部服务调用进行排序的最佳方法

java - 如何使嵌入tomcat的spring boot应用程序能够在weblogic上运行?

javascript - 跨域 REST POST 进行预检但不跟进

database - 502 是数据库错误的适当状态代码吗?

java - SplittableRandom.split() 线程安全吗?

java - 为什么 Autowiring 对于这个 Spring MVC String bean 属性不起作用?

java - 对象映射器给出异常 : com. fastxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段