Spring mvc - 配置 XML 和 JSON 响应的错误处理

Spring mvc - Configuring Error handling for XML and JSON Response

我有一个 REST API 方法:它将 return Xml 作为响应。为简单起见,假设它抛出简单的异常。

@RequestMapping(value = "machine/xmlData", method = RequestMethod.GET, produces = "application/xml")
    public ResponseEntity<String> getXml(HttpServletRequest request)
            throws Exception {
        return getDataFromService();

}

现在我正在像这样处理 REST 控制器中的异常。 这是通用的异常处理方法,也适用于其他 API 方法。(Xml 或 JSON 响应)

 @ExceptionHandler(Exception.class)
        @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
        public ResponseEntity HandleException(Exception ex, HttpServletRequest request) {
            ex.printStackTrace();
           // here logic to generate Custom error Object
            return new ResponseEntity<Object>(customErrorObject, HttpStatus.INTERNAL_SERVER_ERROR);
        }

案例 1: 接受:"application/xml" 和来自服务的有效响应 一切正常。

案例 2: 接受:"application/xml" 和服务异常 然后我得到 406 Not Representable

据我了解是

because ResponseEntity from HandleException is JSON and accept header is "application/xml" thats why i am getting 406.

我是否可以将来自 HandleException 方法的错误 响应发送为 xml 和 json? 我知道在 REST API 方法上我们可以定义这样的东西 produces={"application/json","application/xml"} 我正在努力将它放在 HandleException 方法上。

任何提示都会有很大帮助。

谢谢。

您可以通过使用 @ResponseBody 注释 (https://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc) 来利用 spring-mvc HttpMessageConverters。此注释负责为给定的响应类型选择正确的 messageConverter。

要使您的回复 xml 或 json 兼容,您需要执行以下操作:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class WrappedExceptionResponse {
    public String respone;

    public String getRespone() {
        return respone;
    }

    public void setRespone(String respone) {
        this.respone = respone;
    }
}

并将异常处理方法更改为

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public @ResponseBody WrappedExceptionResponse HandleException(Exception ex, HttpServletRequest request) {
//        ex.printStackTrace();
       // here logic to generate Custom error Object
        WrappedExceptionResponse resp=new WrappedExceptionResponse();
        resp.setRespone(ex.getMessage());
    return resp;

然后您的异常响应将取决于您提供的内容类型。