怎麼在Spring Controller裏面返回404
由於大多的客戶端和服務端是獨立的(可能用不同語言編寫),客戶端無法獲知服務端的異常,所以普通的異常處理並不足以提示客戶端。而基於HTTP協議的服務,我們則需要按照服務端的異常而返回特定的狀態碼給客戶端。
以返回404狀態碼爲例,在Spring 的Controller裏面我們可以有以下3種方式處理:
-
自定義異常+@ResponseStatus註解:
//定義一個自定義異常,拋出時返回狀態碼404 @ResponseStatus(value = HttpStatus.NOT_FOUND) public class ResourceNotFoundException extends RuntimeException { ... } //在Controller裏面直接拋出這個異常 @Controller public class SomeController { @RequestMapping(value="/video/{id}",method=RequestMethod.GET) public @ResponseBody Video getVidoeById(@PathVariable long id){ if (isFound()) { // 做該做的邏輯 } else { throw new ResourceNotFoundException();//把這個異常拋出 } } }
-
使用Spring的內置異常
默認情況下,Spring 的
DispatcherServlet
註冊了DefaultHandlerExceptionResolver
,這個resolver會處理標準的Spring MVC異常來表示特定的狀態碼Exception 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)
-
在Controller方法中通過HttpServletResponse參數直接設值
//任何一個RequestMapping 的函數都可以接受一個HttpServletResponse類型的參數 @Controller public class SomeController { @RequestMapping(value="/video/{id}",method=RequestMethod.GET) public @ResponseBody Video getVidoeById(@PathVariable long id ,HttpServletResponse response){ if (isFound()) { // 做該做的邏輯 } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND);//設置狀態碼 } return .... } }