编程语言
首页 > 编程语言> > java – spring rest处理空请求体(400 Bad Request)

java – spring rest处理空请求体(400 Bad Request)

作者:互联网

我正在使用Spring4开发RESTful应用程序.我想在POST请求中没有传递正文时处理大小写.
我写自定义异常处理程序:

@ControllerAdvice
public class MyRestExceptionHandler {

  @ExceptionHandler
  @ResponseStatus(HttpStatus.BAD_REQUEST)
  public ResponseEntity<MyErrorResponse> handleJsonMappingException(JsonMappingException ex) {
      MyErrorResponse errorResponse = new MyErrorResponse("request has empty body");
      return new ResponseEntity<MyErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
  }   
  @ExceptionHandler(Throwable.class)
  public ResponseEntity<MyErrorResponse> handleDefaultException(Throwable ex) {
    MyErrorResponse errorResponse = new MyErrorResponse(ex);
    return new ResponseEntity<MyErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
  }

}
 @RestController
 public class ContactRestController{
    @RequestMapping(path="/contact", method=RequestMethod.POST)
    public void save(@RequestBody ContactDTO contactDto) {...}
 } 

但是当它发生时,这些方法将不会被调用.我刚收到400 BAD REQUEST http状态和空身的响应.有人知道如何处理吗?

解决方法:

我找到了如何抓住它.我的解决方案是:

    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {

        @Override
        protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
            // paste custom hadling here
        }
    }

标签:java,rest,spring,spring-boot-2,spring-4
来源: https://codeday.me/bug/20190715/1465331.html