如何将消息添加到异常响应

How to add message to response with exception

我接下来使用:java11 + spring-boot:2.4.3.

我在控制器中有下一个方法:

@PutMapping("/{id}")
@ResponseBody
public void update(@PathVariable("id") long id, @RequestBody OrderDto orderDto) {
    try {
        myService.update(id, orderDto);
    } catch (OrderMovementException e) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getLocalizedMessage(), e);
    }
}

好吧,它可以很好地用于测试或记录,我看到了状态和消息。

但是我的前端同事接下来收到,消息是空的:

{"timestamp":"2022-01-24T11:20:48.726+00:00","status":400,"error":"Bad Request","message":"","path":"/service/api/orders/12345"}

我需要更改什么才能解决此问题? 提前致谢。

您的方法可以改为 returning void return class ResponseEntity。请参阅有关如何使用它的文章:Using Spring ResponseEntity to Manipulate the HTTP Response. Another way to provide detailed error message is to write a class annotated with @ControllerAdvice. See some info on that (and other stuff) here: Building REST services with Spring