Grails4 - catching file maxFileSize limit when exceeded on uploading a file

允我心安 提交于 2019-12-14 03:04:26

问题


I would like to catch this exception rather than simply returning a 500 to the end users which is a poor experience, at least in my application. The intention would be to return the user back to the form page with some feedback for them to try again.

The current experience is to throw the user back a 500 and the following is printed to the logs;

Caused by: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (157552) exceeds the configured maximum (1024)

回答1:


Crediting @james-kleeh for this head start;

But I could only get this working on Grails 4.0.0.M2 when I extend the StandardServletMultipartResolver implementation which is what is used as default. Then the maxFileSize limits continue to be resolved from config (yaml).

public class MyMultipartResolver extends StandardServletMultipartResolver {

    static final String FILE_SIZE_EXCEEDED_ERROR = "fileSizeExceeded"

    public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) {
        try {
            return super.resolveMultipart(request)
        } catch (MaxUploadSizeExceededException e) {
            request.setAttribute(FILE_SIZE_EXCEEDED_ERROR, true)
            return new DefaultMultipartHttpServletRequest(request, new LinkedMultiValueMap<String, MultipartFile>(), new LinkedHashMap<String, String[]>(), new LinkedHashMap<String, String>());
        }
    }
}

With the following in resources.groovy;

// catch exception when max file size is exceeded
multipartResolver(MyMultipartResolver)

You need to subsequently check for the FILE_SIZE_EXCEEDED_ERROR attribute in the controller and handle accordingly.



来源:https://stackoverflow.com/questions/56662298/grails4-catching-file-maxfilesize-limit-when-exceeded-on-uploading-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!