2016-11-15 48 views
1

後,我寫了下面的類:春天開機默認的異常處理

@ControllerAdvice 
public class RestExceptionHandler extends ResponseEntityExceptionHandler { 
    @ExceptionHandler(value = Exception.class) 
    @ResponseBody 
    public ResponseEntity<Object> exceptionHandler(Exception e) { 
     HashMap<String, Object> msg = new HashMap<>(2); 
     msg.put("error", HttpStatus.PRECONDITION_FAILED.value()); 
     msg.put("message", "Something went wrong"); 
     return new ResponseEntity<>(msg, HttpStatus.BAD_REQUEST); 
    } 
} 

的意圖是在JSON響應發送msg,而不是放棄Spring異常是什麼原因引發的。

但是,這門課並不適用。

當我打,說,和無效的端點我的服務器API,我得到默認響應有效載荷:

{ 
    "timestamp": 1449238700342, 
    "status": 405, 
    "error": "Method Not Allowed", 
    "exception": "org.springframework.web.HttpRequestMethodNotSupportedException", 
    "message": "Request method 'POST' not supported", 
    "path": "/bad_enpoint" 
} 

我缺少什麼?

謝謝。

+0

你能詳細說明「沒有工作」嗎?它不會被叫?它確實,但失敗了? –

+0

我用更多的信息更新了這個問題。它不會被調用,我仍然是Spring默認的JSON,並且Spring的Expect被「暴露」 – sargas

回答

1

,因爲要映射Exception到您的自定義錯誤響應您的處理程序不會被調用,但Spring MVC很可能已經有一個註冊爲Exception類的異常處理程序。它也有一個處理HttpRequestMethodNotSupportedException肯定。

但是,不管怎樣,重寫整個Spring MVC異常處理/映射並不是一個好主意。您應該只關心特定的例外 - 您定義的例外。

請閱讀this article瞭解Spring MVC異常處理。

+1

感謝您的文章,我很喜歡Spring有自己的處理程序。然而,我不喜歡這樣一個事實,即Spring通過發送類似於「exception」的響應來釋放應用程序的內部:「org.springframework.web.HttpRequestMethodNotSupportedException」,' – sargas

+0

好吧,它是一個有效點。嘗試使用HIGHEST PRECEDENCE集添加@Order註釋。看到這個答案:http://stackoverflow.com/questions/19498378/setting-precedence-of-multiple-controlleradvice-exceptionhandlers –

+0

這個鏈接使用'@ Order'正是我需要的。 – sargas

1
  1. 您不需要擴展ResponseEntityExceptionHandler以使其工作。
  2. 設置兩個HttpStatuses是一個壞主意。

@ControllerAdvice(我不知道爲什麼我必須把它separetly有正確的格式)

public class RestExceptionHandler { 
    @ExceptionHandler(value = Exception.class) 
    @ResponseBody 
    public ResponseEntity<String> exceptionHandler(Exception e) { 
     return new ResponseEntity<>("Something went wrong", HttpStatus.BAD_REQUEST); 
    } 
} 
+0

我仍然得到相同的JSON響應(請參閱我的問題的底部)而不是'「出錯了」' – sargas

+0

@ ControllerAdvice'是控制器的一個方面。你的AJAX調用甚至沒有得到控制器 - 從響應我猜你沒有在'/ bad_enpoint'控制器上執行POST(或根本沒有控制器) –

+0

我有一個定義端點的@ RestController類。應該在同一個類上註釋@RestController和@ControllerAdvice? – sargas