【问题标题】:Throw exception from spring controller which producces xml MediaType从产生 xml MediaType 的弹簧控制器抛出异常
【发布时间】:2015-02-23 13:53:02
【问题描述】:

我有一个带有一个 RequestMapping 的以下控制器,它产生一个 xml MediaType。

 @RestController
    @RequestMapping("/api")
    public class ArticleResource {

    @RequestMapping(value = "/xml/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_XML_VALUE)
        public ResponseEntity<byte[]> getXml(@PathVariable(value = "id") String id,
                                              final HttpServletRequest request,
                                              final HttpServletResponse response) {
            InputStream inputStream = null;
            try {
                inputStream = new FileInputStream(path + id + ".xml");

            } catch (FileNotFoundException e) {
                throw new BadRequestException("No such xml exists");
            }
            try {
                return new ResponseEntity<byte[]>(IOUtils.toByteArray(inputStream), HttpStatus.OK);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new ResponseEntity<byte[]>(HttpStatus.NOT_FOUND);
        }
    }

BadRequestException 实现如下:

@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {

    public BadRequestException(String message) {
        super(message);
    }

}

当 xml 存在时它工作正常,但是当找不到 xml 时我有一个 406 错误代码。我想问题的发生是因为它需要一个 xml 媒体类型,而是返回一个 RuntimeException 。我该如何解决这个问题?

【问题讨论】:

    标签: spring exception-handling


    【解决方案1】:

    您的 HTTP 请求中是否有 Accept: 标头?您的错误处理程序只会返回一个 HTTP 错误代码(响应状态),因此如果客户端需要 XML,它会在客户端导致 406 Not Acceptable。 如果是这种情况,您可以从错误处理程序返回 XML 响应实体并更新您的签名以反映它生成 XML。或者您可以尝试从您的请求中删除Accepts

    【讨论】:

      【解决方案2】:

      我通过返回以下内容解决了我的问题:

      String returnString = "XML file don't exists";
      return new ResponseEntity<byte[]>(IOUtils.toByteArray(
                              new ByteArrayInputStream(returnString.getBytes())), HttpStatus.NOT_FOUND);
      

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        • 2017-03-21
        • 2019-12-09
        • 2020-05-26
        • 1970-01-01
        • 2014-10-28
        相关资源
        最近更新 更多