springmvc 獲取@Requestbody轉(zhuǎn)換的異常處理方式
1、引入問題
使用spring 自動的@RequestBody,可以很方便的將參數(shù)轉(zhuǎn)換成對象,然而在自動轉(zhuǎn)換中出現(xiàn)如果出現(xiàn)異常,會默認直接發(fā)送HTTP異常代碼和錯誤信息,如何才能自定義自己的異常呢。
2、解決方案
解答問題的方式有可以有很多,一種通用的解答方式是使用@ExceptionHandler
2.1 例如傳遞的請求體為JSON時
Spring 可以自動封裝成一個Map
@PostMapping(value = "/check",consumes = "application/json") public ApiResult check(@RequestBody Map<String,String> paramBody) { // ......... }
2.2 如果請求體中是一個非正常的JSON格式
那么會出現(xiàn)異常,可以看到是com.fasterxml.jackson.core.JsonParseException類型的(jackson是spring boot默認的json解析庫)
14:29:40.891 [http-nio-9091-exec-3] WARN o.s.w.s.m.s.DefaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized character escape '[' (code 91); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized character escape '[' (code 91)
返回給前端的可能如下格式的提示,默認的格式不是太好處理
{ "timestamp": 1551680980906, "status": 400, "error": "Bad Request", "message": "JSON parse error: Unrecognized character escape '[' (code 91); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized character escape '[' (code 91)\n at [Source: (PushbackInputStream); line: 66, column: 29]", "path": "/check" }
2.3 自定義錯誤格式輸出
@ExceptionHandler(value = JsonParseException.class) public @ResponseBody ApiResult exceptionHandler(JsonParseException e){ return new ApiResult(500, "調(diào)用接口異常,解析請求體JSON格式錯誤", null); }
2.4 如果還想獲取傳遞的請求體參數(shù)呢
因為請求體是流的形式,只能讀一次,在解析請求體后,流已經(jīng)關閉了。再在上面的代碼中添加request獲取請求體,會得到一個已經(jīng)關閉的流。下面是結(jié)合網(wǎng)上的例子和實踐過的方案
2.4.1 定義一個filter,緩存請求
/** * * @author Bob.chen * @date 2019年3月4日-下午2:10:01 * @desc 包裝下請求,是請求體可以在@ExceptionHandler中使用 */ @Component public class RequestWrapperFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { filterChain.doFilter(new ContentCachingRequestWrapper(httpServletRequest), httpServletResponse); } }
2.4.2 在自定義錯誤格式中使用緩存的請求
@ExceptionHandler(value = JsonParseException.class) public @ResponseBody ApiResult exceptionHandler(JsonParseException e, ServletRequest request) { if (request != null && request instanceof ContentCachingRequestWrapper) { ContentCachingRequestWrapper wrapper = (ContentCachingRequestWrapper) request; LOG.warn("BAD_REQUEST_BODY:{}", StringUtils.toEncodedString(wrapper.getContentAsByteArray(), Charset.forName(wrapper.getCharacterEncoding()))); } return new ApiResult(500, "調(diào)用接口異常,解析請求體JSON格式錯誤", null); }
@RequestBody注解的一些注意事項
1.@RequestBody注解用來獲取請求體中的數(shù)據(jù)
直接使用得到的是key=value&key=value…結(jié)構(gòu)的數(shù)據(jù),因此get方式不適用(get方式下@RequestBody獲取不到任何數(shù)據(jù))。
例:
public void test1(@RequestBody String body){ system.out.println(body); }
輸出結(jié)果:
username=hehe&age=20
2.使用@RequestBody注解后
可以在方法中創(chuàng)建一個集合對象,前端提交的集合數(shù)據(jù)可以直接被注入到方法的集合對象中,而不需要創(chuàng)建一個pojo對象進行集合的封裝。
3.如果想要將前端提交的json字符串自動封裝到一個對象中
需要導入jackson的相關jar包,并使用@RequestBody注解。
注:springmvc默認使用MappingJacksonHttpMessageConverter對json數(shù)據(jù)進行轉(zhuǎn)換。
4.使用@RequestBody
前后端參數(shù)要匹配個數(shù)不能少,字段名字要一樣。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解SpringBoot和Mybatis配置多數(shù)據(jù)源
本篇文章主要介紹了詳解SpringBoot和Mybatis配置多數(shù)據(jù)源,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05sftp和ftp 根據(jù)配置遠程服務器地址下載文件到當前服務
這篇文章主要介紹了sftp和ftp 根據(jù)配置遠程服務器地址下載文件到當前服務的相關資料本文給大家介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2016-10-10Spring Boot配置特定屬性spring.profiles的方法
這篇文章主要介紹了Spring Boot配置特定屬性spring.profiles的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11