如何向异常响应中添加消息

2022-04-16 00:00:00 spring httpresponse java

我使用Next:java11+Spring-Boot:2.4.3.

我在控制器中有Next方法:

@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"}

我需要更改哪些内容才能解决此问题? 提前谢谢。


解决方案

您的方法可以改为或返回空返回类ResponseEntity。有关如何使用它,请参阅一篇文章:Using Spring ResponseEntity to Manipulate the HTTP Response。提供详细错误消息的另一种方法是编写一个用@ControllerAdvice注释的类。请在此处查看有关这方面的信息(以及其他内容):Building REST services with Spring

相关文章