我创建了一个简单的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"
}
我该如何处理这个错误并将其发回给用户。我应该有一个过滤器吗?我应该如何编写这个过滤器?或者应该试一试?
我是新来的春天,但我相信你可以在你的控制器来处理MultipartException写一个异常处理程序。当引发异常时,控制器中的处理程序方法将执行。这里可能会帮助你.https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc – jmw5598