天天看點

Spring MVC處理異常的4種方式

  http://blog.csdn.net/ufo2910628/article/details/40399539

  http://my.oschina.net/CandyDesire/blog/333340

 Spring MVC處理異常有3種方式: 

(1)使用Spring MVC提供的簡單異常處理器SimpleMappingExceptionResolver; 

(2)實作Spring的異常處理接口HandlerExceptionResolver 自定義自己的異常處理器; 

(3)使用@ExceptionHandler注解實作異常處理; 

(4)可以使用 @ControllerAdvice 

     不用任何的配置,隻要把這個類放在項目中,Spring能掃描到的地方。就可以實作全局異常的回調

     來自:http://snowolf.iteye.com/blog/1636050

@ControllerAdvice  
public class SpringExceptionHandler{  
  /** 
     * 全局處理Exception 
     * 錯誤的情況下傳回500 
     * @param ex 
     * @param req 
     * @return 
     */  
    @ExceptionHandler(value = {Exception.class})  
    public ResponseEntity<Object> handleOtherExceptions(final Exception ex, final WebRequest req) {  
        TResult tResult = new TResult();  
        tResult.setStatus(CodeType.V_500);  
        tResult.setErrorMessage(ex.getMessage());  
        return new ResponseEntity<Object>(tResult,HttpStatus.OK);  
    }