2016-06-24 71 views
0

我有方法參數的控制器爲模型說數據綁定在控制器中使用Spring拋出異常

public Response create(Customer customer){ 
    } 

客戶模式:客戶模式看起來像

@JsonTypeInfo( use = JsonTypeInfo.Id.NAME,property = "type") 
@JsonSubTypes({@Type(value = Config.class, name = "IPC")}) 
public class Customer(){ 
private String type; } 
  1. 從招搖UI如果我送鍵入爲IPC工作正常,但除IPC以外的任何其他值都會在綁定時拋出400異常。如何在控制器內捕獲此異常

回答

0

嘗試使用@ExceptionHandler註釋

彈簧4(http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-exceptionhandler)的文檔指出

的HandlerExceptionResolver接口和 的SimpleMappingExceptionResolver實現允許您沿聲明映射 例外具體意見一些可選的 Java邏輯在轉發到那些視圖之前。但是,在某些情況下,特別是在依賴@ResponseBody方法而不是在視圖 分辨率上時,可能更方便直接設置響應的狀態,並可選地將錯誤內容寫入響應的主體。

你可以用@ExceptionHandler方法來做到這一點。當在 控制器中聲明時,此類方法適用於該控制器(或其任何子類)的@RequestMapping 方法引發的異常。您也可以在一個@ControllerAdvice類 中聲明一個@ExceptionHandler方法,在這種情況下,它會處理來自多個控制器的@RequestMapping方法中的異常(從 )。下面是一個控制器本地 @ExceptionHandler方法的一個例子:

所以,在你的控制器,你可以有這樣的

@ExceptionHandler(MethodArgumentNotValidException.class) 
public String handleArgumentNotValid(MethodArgumentNotValidException e, ModelMap map, HttpServletRequest request) { 
    List<ObjectError> errors = e.getBindingResult() .getAllErrors(); 
    //you can get the exception e, 
    //you can get the request 
    //handle whatever you want the then return to view 

    return "your view that you will handle the exception"; 
} 
的方法
相關問題