本文介绍了Spring MVC:在tomcat中的@ResponseBody异常处理程序上使用@ResponseStatus(reason ='')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道为什么我不能在spring MVC中的异常处理程序中使用 @ResponseStatus(reason =我的消息),同时仍然返回@ResponseBody。似乎发生的是,如果我使用原因属性

Does anybody know why I cannot use @ResponseStatus(reason = "My message") on an exception handler in spring MVC while still returning a @ResponseBody. What seems to happen is that if I use the reason attribute

// this exception handle works, the result is a 404 and the http body is the json serialised
// {"message", "the message"}
@ExceptionHandler
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public Map<String, String> notFoundHandler(NotFoundException e){
    return Collections.singletonMap("message", e.getMessage());
}

// this doesn't... the response is a 404 and the status line reads 'Really really not found'
// but the body is actually the standard Tomcat 404 page
@ExceptionHandler
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Really really not found")
public Map<String, String> reallyNotFoundHandler(ReallyNotFoundException e){
    return Collections.singletonMap("message", e.getMessage());
}

在github上结束。

The code for this example is over on github.

推荐答案

这似乎是以下代码的直接结果: AnnotationMethodHandlerExceptionResolver

It seems that this is a direct result of the following code from AnnotationMethodHandlerExceptionResolver

private ModelAndView getModelAndView(Method handlerMethod, Object returnValue, ServletWebRequest webRequest)
        throws Exception {

    ResponseStatus responseStatusAnn = AnnotationUtils.findAnnotation(handlerMethod, ResponseStatus.class);
    if (responseStatusAnn != null) {
        HttpStatus responseStatus = responseStatusAnn.value();
        String reason = responseStatusAnn.reason();
        if (!StringUtils.hasText(reason)) {
            // this doesn't commit the response
            webRequest.getResponse().setStatus(responseStatus.value());
        }
        else {
            // this commits the response such that any more calls to write to the 
            // response are ignored
            webRequest.getResponse().sendError(responseStatus.value(), reason);
        }
    }
    /// snip
}

已在向Springsource报告:

This has been reported to Springsource in SPR-8251:

这篇关于Spring MVC:在tomcat中的@ResponseBody异常处理程序上使用@ResponseStatus(reason ='')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 20:37