springmvc請求參數異常處理


接着上一篇《springmvc 通過異常增強返回給客戶端統一格式》講通過spring ControllerAdvice對各種異常進行攔截處理,統一格式返回給客戶端。

接下來我們更精細的講,通過@ExceptionHandler攔截異常,提示參數客戶端哪些參數沒有傳或參數數據類型不一致,方便客戶端服務端聯調測試。

簡述一下上一篇攔截異常主要流程:

  1.自定義一個類RestExceptionHandler,並使用@ControllerAdvice注解,表示這個類是控制器增強;

  2.在RestExceptionHandler新建一個方法,並使用@ExceptionHandler({Exception.clss})注解在方法上,表示這個方法處理異常信息。

  3.在springMvc.xml里配置

<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" />

  @ExceptionHandler注解允許我們指定異常類型進行攔截處理,也可以對自定義異常攔截。

  那么我們來看看機springmvc對於http請求的異常類型。

Exception Type

HTTP Status Code 

ConversionNotSupportedException

500 (Internal Server Error) 

HttpMediaTypeNotAcceptableException

 

406 (Not Acceptable)  

HttpMediaTypeNotSupportedException

 

415 (Unsupported Media Type) 

HttpMessageNotReadableException

 

400 (Bad Request) 

HttpMessageNotWritableException

 

 500 (Internal Server Error) 

HttpRequestMethodNotSupportedException

 

405 (Method Not Allowed) 

MissingServletRequestParameterException

400 (Bad Request)  

 

NoSuchRequestHandlingMethodException

 

404 (Not Found)  

 

TypeMismatchException

 

400 (Bad Request)

  springmvc內部已經為我們定義好了http請求常見的異常類型,我們只需要使用@ExceptionHandler({MissingServletRequestParameterException.class})注解在方法上,方法參數類型就是我們指定的異常類型,就能獲取到缺少參數異常時的異常對象。

    //參數類型不匹配
	//getPropertyName()獲取數據類型不匹配參數名稱
	//getRequiredType()實際要求客戶端傳遞的數據類型
	@ExceptionHandler({TypeMismatchException.class})
	@ResponseBody
	public String requestTypeMismatch(TypeMismatchException ex){
		ex.printStackTrace();
		return outputJson(-400, "參數類型不匹配,參數" + ex.getPropertyName() + "類型應該為" + ex.getRequiredType());
	}
	//缺少參數異常
	//getParameterName() 缺少的參數名稱
	@ExceptionHandler({MissingServletRequestParameterException.class})
	@ResponseBody
	public String requestMissingServletRequest(MissingServletRequestParameterException ex){
		ex.printStackTrace();
		return outputJson(-400, "缺少必要參數,參數名稱為" + ex.getParameterName());
	}

  

  這樣不管是參數異常,還是數據類型異常,還是請求方法異常,都能做到精細的處理,精確到某個方法的參數和數據類型,給客戶端提示更有意義的信息。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM