弹簧引导休息控制器错误消息始终为空



当调用rest控制器时,抛出错误,Spring引导返回一个JSON错误对象。然而,我的问题是message字段始终为空,即使我向异常提供消息也是如此。错误响应JSON如下所示:

{
"timestamp": "2020-12-23T21:44:30.077+00:00",
"status": 500,
"error": "Internal Server Error",
"message": "",
"path": "/v1/example"
}

在我的代码中,我抛出了这样一个异常:

throw new RuntimeException("HELLO!");

但是字符串msg参数从未出现在响应中。

我知道我可以编写自己的错误处理程序,我正在这样做。但是,如果发生了我没有准备或处理的错误,我希望在响应中显示错误消息,那么Spring引导错误json中的message字段有什么意义?

尝试抛出ResponseStatusException。

throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, "HELLO!");

您的代码是正确的。调试并确保您的RuntimeException正在触发。如果它触发,它肯定会抛出RuntimeException参数中提到的错误消息。

我的猜测是,您的代码在RuntimeException行之前得到了一个错误,所以它不会抛出您的错误消息。

使用此方式抛出错误消息 :

服务类中的某个位置添加以下代码

throw new RuntimeException("Hello");

在控制器类中捕获异常并抛出异常

catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Hello!");
}

完整API样品

@PostMapping(value = "/test-api")
public ResponseEntity<?> sampleMethod(@RequestBody UserDto userDto) {
try {
// Sample code
} catch (RuntimeException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}:

最新更新