【发布时间】:2021-04-14 13:57:10
【问题描述】:
Spring Boot默认不返回任何异常的消息,包括ResponseStatusException,也就是说下面关于bar的消息不会返回给客户端:
@GetMapping("/foo")
@ResponseBody
public Foo getFoo(@RequestParam(name = "bar", defaultValue = "0") int bar) {
if (bar <= 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "bar must always be positive");
}
return example.getFoo(bar);
}
这可以通过在application.properties 中设置server.error.include-message=always 来更改,但是这会导致所有异常消息都返回给客户端,包括这个:
@GetMapping("/baz")
@ResponseBody
public Baz getBaz() {
if (!security.checkSecurity()) {
throw new RuntimeException("Security breach! Hope no one finds out!");
}
return example.getBaz();
}
我知道这是一个简单的示例,解决方案只是“不要从控制器抛出服务器异常”,但异常实际上可能来自深埋在应用程序中的其他代码,甚至可能是 @ 987654328@ 或其他。
如何让应用程序仅显示来自ResponseStatusException 的消息而不显示其他类型的异常? (我想除了在每个控制器方法中添加 try-catch 子句之外。)
【问题讨论】:
-
然后定义您的异常,它将按照您的意愿进行处理。今天检查我以前的答案之一stackoverflow.com/a/67090661/7237884
-
@Boug 这类似于 Akif 的回答。在这里你手动生成
ResponseEntity...我希望Spring从我的ResponseStatusException生成ResponseEntity,否则我觉得使用ResponseStatusException毫无意义。有没有办法告诉 Spring 在您的handleXYZ方法中以默认方式处理ResponseStatusException?
标签: java spring spring-boot