我的Spring Boot应用程序提供以下REST控制器:
@RestController
@RequestMapping("/api/verify")
public class VerificationController {
final VerificationService verificationService;
Logger logger = LoggerFactory.getLogger(VerificationController.class);
public VerificationController(VerificationService verificationService) {
this.verificationService = verificationService;
}
@GetMapping
public void verify(
@RequestParam(value = "s1") String s1,
@RequestParam(value = "s2") String s2) {
try {
verificationService.validateFormat(s1, s2);
} catch (InvalidFormatException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
}
}
}
如果validateFormat()
抛出InvalidFormatException
,客户端将获得正确的HTTP 400。但是,默认的JSON响应主体如下所示:
{
"timestamp": "2020-06-18T21:31:34.911+00:00",
"status": 400,
"error": "Bad Request",
"message": "",
"path": "/api/verify"
}
message
值始终为空,即使我这样对其进行硬编码:
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "some string");
这是异常类:
public class InvalidFormatException extends RuntimeException {
public InvalidFormatException(String s1, String s2) {
super(String.format("Invalid format: [s1: %s, s2: %s]", s1, s2));
}
}
答案 0 :(得分:37)
此行为已在Spring Boot 2.3中更改,并且是故意的。有关详细信息,请参见release notes。
在server.error.include-message=always
中设置application.properties
可解决此问题。
答案 1 :(得分:1)
设置 server.error.include-message=always
会披露内部异常的消息,这可能是生产环境中的问题。
另一种方法是使用 ExceptionHandler
。您可以在此处控制传输到客户端的内容:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<String> handleBadRequestException(ResponseStatusException ex) {
// if you want you can do some extra processing with message and status of an exception
// or you can return it without any processing like this:
return new ResponseEntity<>(ex.getMessage(), ex.getStatus());
}
}