2016-09-18 97 views
0

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

我的控制器看起来像

@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 "[email protected]" 

有了这个请求,一切正常。现在让我们说用户无法附加文件或任何其他不正确的请求,我无法捕获它。它进入调度程序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" 
} 

我该如何处理这个错误并将其发回给用户。我应该有一个过滤器吗?我应该如何编写这个过滤器?或者应该试一试?

+0

我是新来的春天,但我相信你可以在你的控制器来处理MultipartException写一个异常处理程序。当引发异常时,控制器中的处理程序方法将执行。这里可能会帮助你.https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc – jmw5598

回答

0

您可以像下面那样使用@ExceptionHandler方法来处理异常。

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

当春天尝试解析MultipartFile而不能,则抛出异常,并且该exeception的拨款注释的方法将跑。

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

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