반응형
스프링 부트에서 ResponseStatusException을 던질 때 예외 메시지가 응답에 포함되지 않음
My 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));
}
}
이 동작은 Spring Boot 2.3에서 변경되어 의도적인 것입니다.자세한 내용은 릴리스 노트를 참조하십시오.
설정server.error.include-message=always에서application.properties그럼 이 문제가 해결됩니다.
설정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());
}
}
언급URL : https://stackoverflow.com/questions/62459836/exception-message-not-included-in-response-when-throwing-responsestatusexception
반응형
'programing' 카테고리의 다른 글
| wp_enqueue_style이 CSS를 로드하지 않았습니다. (0) | 2023.03.18 |
|---|---|
| C#에서의 JSON 어레이 작성 (0) | 2023.03.18 |
| 에서 들여쓰기된 JSON 문자열을 최소화합니다.그물 (0) | 2023.03.18 |
| 도커: WordPress 컨테이너에 80 이외의 포트를 매핑할 수 없습니다. (0) | 2023.03.18 |
| 개체가 런타임에 TypeScript를 사용하여 인터페이스를 구현하는지 확인합니다. (0) | 2023.03.18 |