Spring HttpServerErrorException自定义响应主体未被序列化

时间:2017-06-08 07:09:54

标签: java spring spring-mvc spring-restcontroller spring-web

我有一个像这个例子的控制器:

@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 。我基本上给它一个转换为字节数组的字符串错误消息列表。

问题是响应正文仍未显示我传递给它的错误消息列表。我试图寻找使用HttpServerErrorException和响应体的示例,但似乎找不到任何帮助...非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

你抛弃了HttpServerErrorException,但没有以正确的方式处理它。

阅读本文:https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc