spring rest处理空请求正文(400错误请求)

问题描述 投票:6回答:4

我正在使用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状态和空身体的回复。有人知道如何处理吗?

java spring rest spring-boot spring-4
4个回答
13
投票

我发现了如何捕捉它。我的解决方案是:

    @ControllerAdvice
    public class RestExceptionHandler extends ResponseEntityExceptionHandler {

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

1
投票

我遇到了类似的问题,因为它提供的component-scan软件包不包括提供我的@ControllerAdvice的软件包,所以它对我不起作用。

我的XML有:

<context:component-scan base-package="com.bandi.rest" />

我的包裹有错别字com.bandi.test.spring.exception。将其更改为com.bandi.rest.spring.exception后,它开始工作。

@ControllerAdvice
public class SpringRestExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public @ResponseBody ResponseEntity<ErrorResponse> handleNoMethodException(HttpServletRequest request,
            NoHandlerFoundException ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        errorResponse.setErrorMessage("resource not found with exception");
        return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Throwable.class)
    public @ResponseBody ResponseEntity<ErrorResponse> handleDefaultException(Throwable ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        errorResponse.setErrorMessage("request has empty body  or exception occured");
        return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
    }
}

此外,如果您需要处理找不到请求的资源(错误的URL)的情况,则必须向调度程序servlet添加另一个配置。

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

完整的工作代码可用here


1
投票

如果您已经有一个用@ControllerAdvice注释的类,并且不想创建新的类,则可以使用这段代码:

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<?> handleMissingRequestBody(Exception ex) {
    return handle(BAD_REQUEST, ex);
}

它的行为应与rvit34的解决方案相同。


0
投票

就我而言,我需要处理所有具有无效参数的请求。所以我用ResponseEntityExceptionHandler扩展了我的类,并覆盖了方法[[handleMissingServletRequestParameter。您可以在类ResponseEntityExceptionHandler

中找到自己定义的处理程序@ ControllerAdvice公共类YourExceptionHandler扩展了ResponseEntityExceptionHandler {

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

}
© www.soinside.com 2019 - 2024. All rights reserved.