Java Spring Boot:处理SizeLimitExceedeException时总是给出;SocketException:软件导致的连接中止:recv failed“;在RestTemplate中
我使用的是Spring boot 1.5.10。我有一个RestController来处理文件上传,我使用restemplate从另一个进程调用它 当我试图上传的文件太大时,Tomcat会触发org.apache.Tomcat.util.http.fileupload.FileUploadBase.sizelimiteExceedeException(如预期的那样)。我想通过返回自定义HTTP响应来很好地处理它,但到目前为止,我的任何尝试似乎都不重要,因为restemplate.exchange总是引发以下异常: org.springframework.web.client.ResourceAccessException:上的I/O错误 发布对“”的请求:软件 导致连接中止:recv失败;嵌套异常是 java.net.SocketException:软件导致的连接中止:recv 失败 到目前为止,我所尝试的:Java Spring Boot:处理SizeLimitExceedeException时总是给出;SocketException:软件导致的连接中止:recv failed“;在RestTemplate中,java,spring,spring-boot,resttemplate,spring-restcontroller,Java,Spring,Spring Boot,Resttemplate,Spring Restcontroller,我使用的是Spring boot 1.5.10。我有一个RestController来处理文件上传,我使用restemplate从另一个进程调用它 当我试图上传的文件太大时,Tomcat会触发org.apache.Tomcat.util.http.fileupload.FileUploadBase.sizelimiteExceedeException(如预期的那样)。我想通过返回自定义HTTP响应来很好地处理它,但到目前为止,我的任何尝试似乎都不重要,因为restemplate.exchange
- 为MultipartException设置ExceptionHandler并处理嵌套FileUploadBase.SizeLimitExceedeException的特殊情况(根据):调用了该处理程序,但仍然得到相同的异常
- 设置ErrorController):调用了错误处理程序,但我仍然得到相同的异常
以下是我的一些代码(仅限有效位): 上传控制器方法:
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(
@RequestParam("file") MultipartFile file
) throws IOException {
// do something with the file
return new ResponseEntity<>("Successfully uploaded '" + file.getOriginalFilename() +"'",
new HttpHeaders(), HttpStatus.OK);
}
RestTemplate restTemplate = new RestTemplate();
URL url = new URL("http", this.targetHostname, this.targetPort, "/upload");
// build request
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new PathResource(path));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);
// perform HTTP request
ResponseEntity<String> result;
try {
result = restTemplate.exchange(
url.toURI(),
HttpMethod.POST,
requestEntity,
String.class);
} catch (RestClientException e) {
log.error("Exception during file upload: ", e);
return;
}
log.debug("Result of upload: " + result);
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
@ExceptionHandler(MultipartException.class)
@ResponseBody
ResponseEntity<?> handleMultipartException(HttpServletRequest request, Throwable ex) throws Throwable {
Throwable cause = ex.getCause();
if (cause instanceof IllegalStateException) {
Throwable cause2 = cause.getCause();
if (cause2 instanceof FileUploadBase.SizeLimitExceededException) {
return new ResponseEntity<>(cause2.toString(), HttpStatus.PAYLOAD_TOO_LARGE);
}
}
throw ex;
}
}
@RestController
public class RestErrorController implements ErrorController {
private static final String PATH = "/error";
@RequestMapping(value = PATH)
public String error() {
return "Some error message";
}
@Override
public String getErrorPath() {
return PATH;
}
}