【问题标题】:How to Response correctly for Current request is not a multipart request in REST如何正确响应当前请求不是 REST 中的多部分请求
【发布时间】:2017-01-26 13:22:02
【问题描述】:

我创建了一个简单的 REST 端点,客户端可以使用 Spring Boot 发布多部分表单数据。 REST 端点接受一个 txt 文件并执行必要的功能。但是当请求无效或不正确时,我无法返回正确的 HTTP 响应。

我的控制器看起来像

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(@RequestParam("file") MultipartFile file) {
    if (!file.isEmpty()) {  
        //perform some steps        
        return "file succesfully creted!";
    }else{
        logger.warn("file is empty");
        return "file wrong";
    }
}

我希望 REST 使用 ResponseEntity 正确发送正确的 HTTP 响应和状态。现在当客户端发出请求时

curl -X POST localhost:8080:/create -F "file=@sample.txt"

有了这个请求,一切正常。现在假设用户未能附加文件或任何其他我无法捕获的错误请求。它进入调度程序 servlet 并引发错误。

{
  "timestamp": 1474236317572,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.springframework.web.multipart.MultipartException",
  "message": "Current request is not a multipart request",
  "path": "/create"
}

如何处理此错误并将其发送回给用户。我应该有一个过滤器吗?我应该如何编写这个过滤器?还是应该有一个 try/catch ?

【问题讨论】:

标签: java spring http servlets multipartform-data


【解决方案1】:

您可以使用@ExceptionHandler 方法处理异常,如下所示。

@ExceptionHandler(MultipartException.class)
public ResponseEntity<String> handleMultipartException(HttpServletRequest request, Exception e) {
    return new ResponseEntity<>("Error: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}

当 spring 尝试解析 MultipartFile 并且无法解析时,将引发异常并运行该异常的适当注释方法。

编辑:这里有一些可能有用的资源。

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc https://www.youtube.com/watch?v=oG2rotiGr90

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-27
    • 2017-06-20
    • 1970-01-01
    • 2021-11-16
    • 2012-08-12
    • 1970-01-01
    • 2019-09-16
    • 2020-05-25
    相关资源
    最近更新 更多