Spring 启动 @ResponseStatus 不返回 HTTP 消息
Spring Boot @ResponseStatus not returning HTTP message
我在抛出异常时返回 HTTP 消息时遇到问题。我正在使用 @ResponseStatus 注释来处理 HTTP 状态代码,它显示正常但消息被忽略。
自定义异常:
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "An error ocurred while trying to
retrieve the instruments.")
public class InstrumentsNotFoundException extends RuntimeException {
private static final Logger logger = LoggerFactory.getLogger(InstrumentsNotFoundException.class);
public InstrumentsNotFoundException(String errorMessage) {
super(errorMessage);
logger.error(errorMessage);
}
控制器:
@GetMapping({ "/portfolio/" })
public List<Instrument> getAll() {
try {
List<Instrument> instruments= portfolioYieldProcessor.getPortfolio();
return instruments;
} catch(RuntimeException e) {
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, "Sorry, an error occurred, please try again later.", e);
}
}
HttpMessage
从 SpringBoot 2.3 开始,这是默认行为,如您所见here。
假设您使用的是 spring 2.3+
server.error.include-message=always
在您的 application.properties 中将为您解决问题。
我在抛出异常时返回 HTTP 消息时遇到问题。我正在使用 @ResponseStatus 注释来处理 HTTP 状态代码,它显示正常但消息被忽略。
自定义异常:
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "An error ocurred while trying to
retrieve the instruments.")
public class InstrumentsNotFoundException extends RuntimeException {
private static final Logger logger = LoggerFactory.getLogger(InstrumentsNotFoundException.class);
public InstrumentsNotFoundException(String errorMessage) {
super(errorMessage);
logger.error(errorMessage);
}
控制器:
@GetMapping({ "/portfolio/" })
public List<Instrument> getAll() {
try {
List<Instrument> instruments= portfolioYieldProcessor.getPortfolio();
return instruments;
} catch(RuntimeException e) {
throw new ResponseStatusException(
HttpStatus.INTERNAL_SERVER_ERROR, "Sorry, an error occurred, please try again later.", e);
}
}
HttpMessage
从 SpringBoot 2.3 开始,这是默认行为,如您所见here。
假设您使用的是 spring 2.3+
server.error.include-message=always
在您的 application.properties 中将为您解决问题。