2011-04-12 60 views
6

在@ResponseBody異常處理程序使用@ResponseStatus(原因=「」)是否有人知道我爲什麼不能在春天MVC異常處理程序使用@ResponseStatus(reason = "My message"),同時還返回@ResponseBody。有什麼事發生的是,如果我用reason屬性Spring MVC的:在Tomcat中

// 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()); 
} 

code for this example是在GitHub上。

+0

同樣的問題在這裏:http://stackoverflow.com/questions/ 29075160 /無responsebody - 返回 - 從-的ExceptionHandler功能於彈簧啓動應用程序部署,在 – 2015-03-26 06:19:35

回答

5

看來,這是從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在SPR-8251下面的代碼的直接結果是:由於春季3.2

3

根據記錄,這讓更糟糕因爲AnnotationMethodHandlerExceptionResolver已取代了ResponseStatusExceptionResolver和它的作用:

ŧ他值得一個錯誤報告。此外,@ResponseStatus記錄爲setStatus,並且設計不合理。它應該被稱爲@ResponseError

我已經創建了兩個問題,這最後:SPR-11192SPR-11193

差不多一年過去了,我的兩個問題仍然沒有解決。我不認爲Spring WebMVC作爲一流的REST框架,它不是imho,Web MVC用於humas而不是機器:-(

+0

@BartoszKP你爲什麼要刪除我的答案編輯? – 2015-08-28 17:00:52

+1

1)我只編輯了「編輯指標」。答案應該作爲一個整體來說是一致的,事實上哪一部分是與一個尋求解決問題的人完全無關的。如果有人對帖子的歷史感興趣,它仍然很容易獲得。 2)這不是你的答案。你是作者,但它屬於SO。 – BartoszKP 2015-08-29 10:35:17

+0

@BartoszKP可笑,認真! – 2015-08-29 19:09:50