[英]Which exception should be thrown, when Spring SecurityContextHolder returns null on getPrincipal?
[英]Java Spring - Handle exception thrown when @RequestBody is null
我在 Java Z38008DD81C2F4D79185ECF6E0CE8AF1D1D 中有一個 rest Java Spring Boot
。 我正在向api
發出POST
請求。 如果正文中有數據,它可以正常工作,但是當沒有數據傳遞時,它會給出400 Bad Request
響應:
{
"timestamp": "2021-05-03T13:32:36.746+0000",
"status": 400,
"error": "Bad Request",
"message": "Required request body is missing: public org.springframework.http.ResponseEntity<com.package.MyResponse> com.package.MyController.getData(com.package.MyRequest)",
"path": "/api/"
}
如何從響應消息中隱藏package information
和class name
? 它應該返回消息:
"message": "Required request body is missing."
一種選擇是設置@RequestBody(required=false)
然后在里面手動處理,但我想避免。
如果有人可以提供幫助,那就太好了。 謝謝你。
您可以創建一個RestControllerAdvice
並使用ResponseEntityExceptionHandler
對其進行擴展。 在實現中覆蓋相應的方法並發送您的自定義消息。 在您的情況下,方法將是來自ResponseEntityExceptionHandler
的handleHttpMessageNotReadable
。
這是示例代碼:
/**
* Intercept exception to response with error
*/
@RestControllerAdvice
public class ApplicationExceptionHandler extends ResponseEntityExceptionHandler {
/**
* {@inheritDoc}
*/
@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
// your custom implementation
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.