处理空的请求体(400错误请求)的Spring REST

15 浏览
0 Comments

处理空的请求体(400错误请求)的Spring REST

我正在使用Spring4开发一个RESTful应用程序。

当POST请求不包含请求体时,我想处理它。我编写了以下自定义异常处理程序:

    @ControllerAdvice
    public class MyRestExceptionHandler {
      @ExceptionHandler
      @ResponseStatus(HttpStatus.BAD_REQUEST)
      public ResponseEntity handleJsonMappingException(JsonMappingException ex) {
          MyErrorResponse errorResponse = new MyErrorResponse("request has empty body");
          return new ResponseEntity(errorResponse, HttpStatus.BAD_REQUEST);
      }   
      @ExceptionHandler(Throwable.class)
      public ResponseEntity handleDefaultException(Throwable ex) {
        MyErrorResponse errorResponse = new MyErrorResponse(ex);
        return new ResponseEntity(errorResponse, HttpStatus.BAD_REQUEST);
      }
    }
     @RestController
     public class ContactRestController{
        @RequestMapping(path="/contact", method=RequestMethod.POST)
        public void save(@RequestBody ContactDTO contactDto) {...}
     } 

但是,当它接收到没有请求体的POST请求时,这些方法不会被调用。相反,客户端会收到一个带有400 BAD REQUEST HTTP状态和空响应体的响应。有没有人知道如何处理它?

admin 更改状态以发布 2023年5月21日
0
0 Comments

在我的情况下,我需要处理所有具有无效参数的请求。因此,我通过扩展我的类与ResponseEntityExceptionHandler并重写方法handleMissingServletRequestParameter。您可以在ResponseEntityExceptionHandler类中找到自己定义的处理程序

@ControllerAdvice 
public class YourExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(Exception.class)
    public final ResponseEntity handleAllExceptions(Exception ex) {
        // Log and return
    }
    @Override
    public ResponseEntity handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // Do your code here
        return new ResponseEntity<>("YOUR REQUEST PARAMS NOT MATCH!");
    } 
}

0
0 Comments

我解决了这个问题(自定义异常处理程序必须扩展 ResponseEntityExceptionHandler)。我的解决方案如下:

        @ControllerAdvice
        public class RestExceptionHandler extends ResponseEntityExceptionHandler {
            @Override
            protected ResponseEntity handleHttpMessageNotReadable(
                HttpMessageNotReadableException ex, HttpHeaders headers,
                HttpStatus status, WebRequest request) {
                // paste custom hadling here
            }
        }

0