简体   繁体   中英

Spring HttpServerErrorException custom response body not being serialized

I have a Controller like this example:

@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;
        }       
    }
}

When posting the inputs to the controller and a CustomException occurs, I instantiate HttpServerErrorException using the constructor that accepts a byte array for responseBody . I basically give it a list of String error messages converted to byte array.

The problem is the response body still does not show the list of errors messages I passed to it. I tried looking for examples on using HttpServerErrorException with response body but cannot seem to find any... Any help would be greatly appreciated.

You throw your HttpServerErrorException but don't handle it in the proper way.

Read this: https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM