[英]Spring HttpServerErrorException custom response body not being serialized
我有一個像這個例子的控制器:
@RestController
@RequestMapping(value = "/risk", produces = {MediaType.APPLICATION_JSON_VALUE})
public class CalculationController {
@RequestMapping(value = "/calculate", method = RequestMethod.POST)
public CalculationResult calculate(InputFields i) {
try {
return calcService.calculate(i);
} catch (CustomException custEx) {
throw new HttpServerErrorException(HttpStatus.INTERNAL_SERVER_ERROR,
null,
null,
getReportLogAsBytes(custEx), //for some reason not working when serialized in Json
Charset.defaultCharset());
}
}
private byte[] getReportLogAsBytes(CustomException e) {
try {
return objectMapper.writeValueAsBytes(e.getReportLog()); //
} catch (JsonProcessingException e1) {
throw new RuntimeException("Unable to serialize Simulation report log to bytes ", e1);
}
}
class CustomException extends Exception {
private List<String> reportLog;
public CustomException(List<String> reportLog) {
super();
this.setReportLog(reportLog);
}
public List<String> getReportLog() {
return reportLog;
}
public void setReportLog(List<String> reportLog) {
this.reportLog = reportLog;
}
}
}
當將輸入發布到控制器並發生CustomException時,我使用接受為responseBody的字節數組的構造函數實例化HttpServerErrorException 。 我基本上給它一個轉換為字節數組的String錯誤消息列表。
問題是響應正文仍未顯示我傳遞給它的錯誤消息列表 。 我嘗試尋找有關將HttpServerErrorException與響應正文一起使用的示例,但似乎找不到任何...任何幫助將不勝感激。
您拋出了HttpServerErrorException
但沒有以正確的方式處理它。
閱讀此內容: https : //spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.