org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing
出現(xiàn)異常的原因:body為空,但是@RequestBody注解默認請求體不能為空。
解決辦法
一:查看是不是@GetMapping,Spring Get請求不能使用@RequestBody
這個純屬粗心大意的問題~
二:要求請求用Post卻用了Get請求
三:@RequestBody(required = false)
如果是剛剛開發(fā)的項目,那么建議這樣寫。如果已經(jīng)存在的項目,肯定不能這樣寫,后面會介紹另外一種相對簡單的寫法,但是如果Spring版本升級有可能會出現(xiàn)問題。文章來源:http://www.zghlxwxcb.cn/news/detail-647034.html
@PostMapping("postUrl")
public void postUrl(@RequestBody(required = false) Object object){
if (object == null){
throw new RuntimeException("post請求體body不能為空!");
}
}
四:全局異常捕獲
如果Spring 版本升級有可能會改變該信息,因此升級版本后如果字符串信息改變也要做出相應的改變,不過這種概率比較低!可以放心使用。文章來源地址http://www.zghlxwxcb.cn/news/detail-647034.html
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局返回和異常處理類
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 服務器異常
*/
@ExceptionHandler(value =Exception.class)
public Object exception(Exception e){
String msg = e.getMessage();
if (StringUtils.hasText(msg)){
//捕獲這個異常信息,如果這個異常信息包含這個字符串就拋出自定義異常。
if (msg.contains("Required request body is missing:")){
throw new RuntimeException("post請求體body不能為空!");
}
}
log.error("Exception異常:",e);
return msg;
}
}
到了這里,關于SpringBoot之Post請求@RequestBody為空拋出Required request body is missing異常的解決方案的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!