Tin*_*iny 12 spring exception-handling file-upload spring-mvc handlerexceptionresolver
我正在使用Spring 3.2.0.根据这个答案,我在带注释的控制器中使用相同的方法来实现HandlerExceptionResolver接口,例如:
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {
Map<String, Object> model = new HashMap<String, Object>(0);
if (exception instanceof MaxUploadSizeExceededException) {
model.put("msg", exception.toString());
model.put("status", "-1");
} else {
model.put("msg", "Unexpected error : " + exception.toString());
model.put("status", "-1");
}
return new ModelAndView("admin_side/ProductImage");
}
Run Code Online (Sandbox Code Playgroud)
和Spring配置包括,
<bean id="filterMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>10000</value>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
当文件大小超过时,应该调用前面的方法,它应该自动处理异常,但根本不会发生.resolveException()即使发生异常,也不会调用该方法.处理此异常的方法是什么?我错过了什么吗?
这里也指出了同样的事情.我不确定为什么它在我的情况下不起作用.
我尝试了以下方法,@ControllerAdvice但它也没有用.
package exceptionhandler;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
@ControllerAdvice
public final class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {MaxUploadSizeExceededException.class})
protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
String bodyOfResponse = "This should be application specific";
return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(), HttpStatus.CONFLICT, request);
}
}
Run Code Online (Sandbox Code Playgroud)
我也试图把冗长 - Exception.
@ExceptionHandler(value={Exception.class})
Run Code Online (Sandbox Code Playgroud)
ResponseEntity()在任何情况下都不会调用该方法.
通常,如果可能的话,我想在每个控制器基础(控制器级别)处理此异常.为此,一个带@ExceptionHandler注释的方法应仅对该特定控制器是活动的,而不是对整个应用程序是全局的,因为我的应用程序中只有少数网页处理文件上载.当引起此异常时,我只想在当前页面上显示用户友好的错误消息,而不是重定向到web.xml文件中配置的错误页面.如果这甚至不可行,那么无论如何都应该处理这个异常而没有我刚才表达的任何自定义要求.
这两种方法都不适合我.我找不到更多关于处理这个例外的事情.是否需要在XML文件或其他地方进行其他配置?
抛出异常后我得到的内容可以在下面的快照中看到.

根据您发布的stacktrace,在请求到达调度程序servlet 之前MaxUploadSizeExceeded抛出异常.因此,不会调用异常处理程序,因为在抛出异常时,目标控制器尚未确定.
如果你看一下堆栈跟踪,你会发现在HiddenHttpMethodFilter获取你的multipart-request的所有参数 - 以及你的"to big"upload-data参数时会抛出异常.
HiddenHttpMethodFilter您的控制器是否需要处理多部分上传?如果没有,请从上传处理控制器中排除此过滤器.
| 归档时间: |
|
| 查看次数: |
7009 次 |
| 最近记录: |