Boot返回JSON错误消息的异常

Boot返回JSON错误消息的异常

本文介绍了分段文件上传:大小超出Spring Boot返回JSON错误消息的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我设置了最大文件上传限制,所以我得到

As I have set maximum file upload limit,I am getting

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field file exceeds its maximum permitted size of 2097152 bytes

上载文件时出现

错误.它给我的api带来了500错误,我应该处理此错误并以JSON格式返回响应,而不是ErrorController

error while uploading file.It is giving 500 error to my api,I should I handle this error and return response in JSON format not an errorpage as provided in ErrorController

我想捕获该异常,而不是ErrorPage给出JSON响应.

I want to catch that exception and give JSON response not ErrorPage.

@RequestMapping(value="/save",method=RequestMethod.POST)
    public ResponseDTO<String> save(@ModelAttribute @Valid FileUploadSingleDTO fileUploadSingleDTO,BindingResult bindingResult)throws MaxUploadSizeExceededException
    {
        ResponseDTO<String> result=documentDetailsService.saveDocumentSyn(fileUploadSingleDTO, bindingResult);

        return result;

    }

接受文档的DTO如下

public class FileUploadSingleDTO {
@NotNull
    private Integer documentName;

    private Integer documentVersion;

    @NotNull
    private MultipartFile file;
}

推荐答案

据我所知,您可以使用此方法处理多部分文件异常.

As par I know you can handle the multipart file exception by using this.

@ControllerAdvice
public class MyErrorController extends ResponseEntityExceptionHandler {

Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());

@ExceptionHandler(MultipartException.class)
@ResponseBody
String handleFileException(HttpServletRequest request, Throwable ex) {
    //return your json insted this string.
    return "File upload error";
  }
}

这篇关于分段文件上传:大小超出Spring Boot返回JSON错误消息的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:00