Spring ResponseStatusException 不返回原因

新手上路,请多包涵

我有一个非常简单的 @RestController ,我正在尝试设置自定义错误消息。但由于某种原因,错误的 message 没有出现。

这是我的控制器:

 @RestController
@RequestMapping("openPharmacy")
public class OpenPharmacyController {

    @PostMapping
    public String findNumberOfSurgeries(@RequestBody String skuLockRequest) {
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "This postcode is not valid");
    }

}

这是我得到的回应:

 {
    "timestamp": "2020-06-24T17:44:20.194+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "",
    "path": "/openPharmacy/"
}

我正在传递一个 JSON,但我没有验证任何东西,我只是想设置自定义消息。如果我更改状态代码,我会在响应中看到它,但 message 始终为空。

为什么这不像预期的那样工作?这是一个如此简单的示例,我看不出可能缺少什么。当我调试代码时,我可以看到错误消息已设置所有字段。但由于某种原因,消息永远不会在响应中设置。

原文由 cunhaf 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 904
2 个回答

该答案由用户 Hassan 在对原始问题的评论中提供。我只是将其作为答案发布,以提高可见度。

基本上,您需要做的就是将 server.error.include-message=always 添加到您的 application.properties 文件中,现在应该填充您的消息字段。

此行为在 Spring Boot 2.3 中已更改,您可以在此处阅读: https ://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default -错误页面内容

原文由 np_ 发布,翻译遵循 CC BY-SA 4.0 许可协议

我有同样的问题。如果我使用这个结构

throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Error in update");

我的消息未通过 JSON 传递给客户端。对我来说,解决它的唯一方法是创建 GlobalExceptionHandler

package mypackage;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.Date;

@ControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(NotFoundException.class)
  public ResponseEntity<ErrorDTO> generateNotFoundException(NotFoundException ex) {
    ErrorDTO errorDTO = new ErrorDTO();
    errorDTO.setMessage(ex.getMessage());
    errorDTO.setStatus(String.valueOf(ex.getStatus().value()));
    errorDTO.setTime(new Date().toString());

    return new ResponseEntity<ErrorDTO>(errorDTO, ex.getStatus());
  }
}

我还创建了自己的 Exception 类型

package mypackage;

import org.springframework.http.HttpStatus;

public class NotFoundException extends RuntimeException {

  public NotFoundException(String message) {
    super(message);
  }

  public HttpStatus getStatus() {
    return HttpStatus.NOT_FOUND;
  }
}

有了这个,我能够从控制器中抛出异常,并且我在 JSON 中得到了正确的结果——我想看到的消息。

 @PutMapping("/data/{id}")
public DataEntity updateData(@RequestBody DataEntity data, @PathVariable int id) {
  throw new NotFoundException("Element not found");
}

我还必须介绍 ErrorDTO

 package mypackage;

public class ErrorDTO {
  public String status;
  public String message;
  public String time;

  ...
  ...
  // getters and setters are here
  ...
  ...
}

更新

正如@Hassan 和@cunhaf 所提到的(在原始问题下的评论中),解决方案是

server.error.include-message=always

ResponseStatusException 完美配合。尽管如此,如果有人想通过异常传递更多信息,使用 GlobalExceptionHandler 的解决方案可能会更好。

源代码

示例可在此处找到: 全局异常处理 程序

原文由 Oo.oO 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题