@ExceptionHandler({ InvalidArgumentException.class, MalformedTemplateException.class, MissingServletRequestParameterException.class, MissingServletRequestPartException.class, ServletRequestBindingException.class }) @ResponseStatus(code = HttpStatus.BAD_REQUEST) @ResponseBody public void handleMissingAndMalformedParametersValues(Exception exception) { log.error("Input parameters were missing/malformed:", exception); }
@Override protected void handleMissingValue(String name, MethodParameter parameter, NativeWebRequest request) throws Exception { HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class); if (MultipartResolutionDelegate.isMultipartArgument(parameter)) { if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) { throw new MultipartException("Current request is not a multipart request"); } else { throw new MissingServletRequestPartException(name); } } else { throw new MissingServletRequestParameterException(name, parameter.getNestedParameterType().getSimpleName()); } }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { //取出存入的用户ID String currentUserId = (String) webRequest.getAttribute(Constant.CURRENT_USER_ID, RequestAttributes.SCOPE_REQUEST); if (currentUserId != null) { return userDao.findById(currentUserId); } return new MissingServletRequestPartException(Constant.CURRENT_USER_ID); }
@Override protected ResponseEntity<Object> handleMissingServletRequestPart(final MissingServletRequestPartException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { logger.info(ex.getClass().getName()); // final String error = ex.getRequestPartName() + " part is missing"; final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); }
@Override protected ResponseEntity<Object> handleMissingServletRequestPart(final MissingServletRequestPartException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { logger.info(ex.getClass().getName()); // final String error = ex.getRequestPartName() + " part is missing"; final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error); return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request); }
@Test public void handleMissingServletRequestPartException() throws Exception { MissingServletRequestPartException ex = new MissingServletRequestPartException("name"); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); assertNotNull("No ModelAndView returned", mav); assertTrue("No Empty ModelAndView returned", mav.isEmpty()); assertEquals("Invalid status code", 400, response.getStatus()); assertEquals("Required request part 'name' is not present.", response.getErrorMessage()); }
@Test public void resolveRequestPartRequired() throws Exception { try { testResolveArgument(null, paramValidRequestPart); fail("Expected exception"); } catch (MissingServletRequestPartException ex) { assertEquals("requestPart", ex.getRequestPartName()); } }
@Override protected ResponseEntity<Object> handleMissingServletRequestPart( MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, WebRequest request ) { headers.add( "Content-Type", MediaType.APPLICATION_JSON_VALUE ); return new ResponseEntity<>( MessageUtils.jsonMessage( Integer.toString( status.value() ), ex.getMessage() ), status ); }
@Test public void resolveRequestPartRequired() throws Exception { try { testResolveArgument(null, paramValidRequestPart); fail("Expected exception"); } catch (MissingServletRequestPartException e) { assertEquals("requestPart", e.getRequestPartName()); } }
/** * {@link MissingServletRequestPartException}をハンドリングします。 * @param e {@link MissingServletRequestPartException} * @return {@link ErrorMessage} * HTTPステータス 400 でレスポンスを返却します。 */ @ExceptionHandler(MissingServletRequestPartException.class) @ResponseBody @ResponseStatus(value = HttpStatus.BAD_REQUEST) @Override public ErrorMessage handle(MissingServletRequestPartException e) { if (L.isDebugEnabled()) { L.debug(R.getString("D-SPRINGMVC-REST-HANDLER#0011"), e); } ErrorMessage error = createClientErrorMessage(HttpStatus.BAD_REQUEST); warn(error, e); return error; }
@Test public void MissingServletRequestPartExceptionをハンドリングできる() { MissingServletRequestPartException ex = new MissingServletRequestPartException("partName"); ErrorMessage message = this.exceptionHandlerSupport.handle(ex); assertThat(message, notNullValue()); assertThat(message.getStatus(), is(400)); assertThat(message.getMessage(), is("不正なリクエストです。")); }
/** * 파라미터 검증 실패. * * multipart/form-data 에서 key가 file이 아닐때. */ @Override protected ResponseEntity<Object> handleMissingServletRequestPart(MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ServiceError serviceError = ServiceError.FORM_VALIDATION_FAILED; RestErrorResponse restErrorResponse = new RestErrorResponse(serviceError); try { log.warn(ObjectMapperUtils.writeValueAsString(restErrorResponse), ex); } catch (JsonProcessingException ignore) { log.warn(ex.getLocalizedMessage(), ex); } return new ResponseEntity<>(restErrorResponse, HttpStatus.valueOf(serviceError.getHttpStatus())); }
private Map<Class, RestExceptionHandler> getDefaultHandlers() { Map<Class, RestExceptionHandler> map = new HashMap<>(); map.put( NoSuchRequestHandlingMethodException.class, new NoSuchRequestHandlingMethodExceptionHandler() ); map.put( HttpRequestMethodNotSupportedException.class, new HttpRequestMethodNotSupportedExceptionHandler() ); map.put( HttpMediaTypeNotSupportedException.class, new HttpMediaTypeNotSupportedExceptionHandler() ); map.put( MethodArgumentNotValidException.class, new MethodArgumentNotValidExceptionHandler() ); if (ClassUtils.isPresent("javax.validation.ConstraintViolationException", getClass().getClassLoader())) { map.put( ConstraintViolationException.class, new ConstraintViolationExceptionHandler() ); } addHandlerTo( map, HttpMediaTypeNotAcceptableException.class, NOT_ACCEPTABLE ); addHandlerTo( map, MissingServletRequestParameterException.class, BAD_REQUEST ); addHandlerTo( map, ServletRequestBindingException.class, BAD_REQUEST ); addHandlerTo( map, ConversionNotSupportedException.class, INTERNAL_SERVER_ERROR ); addHandlerTo( map, TypeMismatchException.class, BAD_REQUEST ); addHandlerTo( map, HttpMessageNotReadableException.class, UNPROCESSABLE_ENTITY ); addHandlerTo( map, HttpMessageNotWritableException.class, INTERNAL_SERVER_ERROR ); addHandlerTo( map, MissingServletRequestPartException.class, BAD_REQUEST ); addHandlerTo(map, Exception.class, INTERNAL_SERVER_ERROR); // this class didn't exist before Spring 4.0 try { Class clazz = Class.forName("org.springframework.web.servlet.NoHandlerFoundException"); addHandlerTo(map, clazz, NOT_FOUND); } catch (ClassNotFoundException ex) { // ignore } return map; }
@GetMapping("/test/missing-servlet-request-part") public void missingServletRequestPartException() throws Exception { throw new MissingServletRequestPartException("missing Servlet request part"); }
public <T extends Throwable> ErrorDataProvider getErrorDataProvider(T ex) { if (ex instanceof ApplicationException) { return new ApplicationErrorDataProvider(errorestProperties); } if (ex instanceof ExternalHttpRequestException) { return new ExternalHttpRequestErrorDataProvider(errorestProperties); } if (ex instanceof BindException) { return new BindExceptionErrorDataProvider(errorestProperties); } if (ex instanceof MethodArgumentNotValidException) { return new MethodArgumentNotValidErrorDataProvider(errorestProperties); } if (ex instanceof HttpMediaTypeNotAcceptableException) { return new MediaTypeNotAcceptableErrorDataProvider(errorestProperties); } if (ex instanceof HttpMediaTypeNotSupportedException) { return new MediaTypeNotSupportedErrorDataProvider(errorestProperties); } if (ex instanceof HttpRequestMethodNotSupportedException) { return new RequestMethodNotSupportedErrorDataProvider(errorestProperties); } if (ex instanceof MissingServletRequestParameterException) { return new MissingServletRequestParameterErrorDataProvider(errorestProperties); } if (ex instanceof HttpMessageNotReadableException) { return new MessageNotReadableErrorDataProvider(errorestProperties); } if (ex instanceof MissingServletRequestPartException) { return new MissingServletRequestPartErrorDataProvider(errorestProperties); } if (ex instanceof NoHandlerFoundException) { return new NoHandlerFoundErrorDataProvider(errorestProperties); } if (ex instanceof ServletRequestBindingException) { return new ServletRequestBindingErrorDataProvider(errorestProperties); } if (ex instanceof TypeMismatchException) { return new TypeMismatchErrorDataProvider(errorestProperties); } return new ThrowableErrorDataProvider(errorestProperties); }
@Override public ErrorData getErrorData(MissingServletRequestPartException ex, HttpServletRequest request) { return getErrorData(ex, request, BAD_REQUEST); }
@Override public ErrorData getErrorData(MissingServletRequestPartException ex, HttpServletRequest request, HttpStatus responseHttpStatus, ErrorAttributes errorAttributes, RequestAttributes requestAttributes) { return super.getErrorData(ex, request, BAD_REQUEST, errorAttributes, requestAttributes); }
@Override protected String getErrorDescription(MissingServletRequestPartException ex) { return BAD_REQUEST.getReasonPhrase() + ", " + uncapitalize(ex.getMessage()); }
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!requestMatcher.matches(request)) { filterChain.doFilter(request, response); return; } String uri = request.getRequestURI(); if (uri.endsWith("/exception")) { throw new RuntimeException("Exception from servlet filer"); } if (uri.endsWith("/media-type-not-acceptable")) { throw new HttpMediaTypeNotAcceptableException(asList(APPLICATION_JSON, APPLICATION_XML)); } if (uri.endsWith("/media-type-not-supported")) { throw new HttpMediaTypeNotSupportedException(TEXT_HTML, singletonList(TEXT_PLAIN)); } if (uri.endsWith("/message-not-readable")) { throw new HttpMessageNotReadableException("Message not readable from servlet filter"); } if (uri.endsWith("/missing-servlet-request-parameter")) { throw new MissingServletRequestParameterException("query-parameter", "String"); } if (uri.endsWith("/missing-servlet-request-part")) { throw new MissingServletRequestPartException("part"); } if (uri.endsWith("/no-handler-found")) { throw new NoHandlerFoundException(request.getMethod(), request.getRequestURI(), null); } if (uri.endsWith("/request-method-not-supported")) { throw new HttpRequestMethodNotSupportedException(request.getMethod(), singletonList("DELETE")); } if (uri.endsWith("/servlet-request-binding")) { throw new ServletRequestBindingException("Exception from servlet filter"); } if (uri.endsWith("/type-mismatch")) { String parameter = request.getParameter("query-parameter"); NumberFormatException ex = new NumberFormatException("For input string: \"" + parameter + "\""); throw new MethodArgumentTypeMismatchException(parameter, int.class, null, null, ex); } if (uri.endsWith("/application")) { throw new TestApplicationException(); } if (uri.endsWith("/external-request")) { rest.getForObject("http://localhost:10000/external/resource", String.class); } if (uri.endsWith("/access-denied")) { throw new AccessDeniedException("Access denied from servlet filter"); } if (uri.endsWith("/authentication-error")) { throw new BadCredentialsException("Access denied from servlet filter"); } if (uri.endsWith("/no-error")) { prepareResponse(request, response); } else { filterChain.doFilter(request, response); } }
@Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { try { if (ex instanceof NoSuchRequestHandlingMethodException) { return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response, handler); } else if (ex instanceof HttpRequestMethodNotSupportedException) { return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request, response, handler); } else if (ex instanceof HttpMediaTypeNotSupportedException) { return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, request, response, handler); } else if (ex instanceof HttpMediaTypeNotAcceptableException) { return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, request, response, handler); } else if (ex instanceof MissingPathVariableException) { return handleMissingPathVariable((MissingPathVariableException) ex, request, response, handler); } else if (ex instanceof MissingServletRequestParameterException) { return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, request, response, handler); } else if (ex instanceof ServletRequestBindingException) { return handleServletRequestBindingException((ServletRequestBindingException) ex, request, response, handler); } else if (ex instanceof ConversionNotSupportedException) { return handleConversionNotSupported((ConversionNotSupportedException) ex, request, response, handler); } else if (ex instanceof TypeMismatchException) { return handleTypeMismatch((TypeMismatchException) ex, request, response, handler); } else if (ex instanceof HttpMessageNotReadableException) { return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, request, response, handler); } else if (ex instanceof HttpMessageNotWritableException) { return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, request, response, handler); } else if (ex instanceof MethodArgumentNotValidException) { return handleMethodArgumentNotValidException((MethodArgumentNotValidException) ex, request, response, handler); } else if (ex instanceof MissingServletRequestPartException) { return handleMissingServletRequestPartException((MissingServletRequestPartException) ex, request, response, handler); } else if (ex instanceof BindException) { return handleBindException((BindException) ex, request, response, handler); } else if (ex instanceof NoHandlerFoundException) { return handleNoHandlerFoundException((NoHandlerFoundException) ex, request, response, handler); } } catch (Exception handlerException) { if (logger.isWarnEnabled()) { logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException); } } return null; }
@Override @UsesJava8 public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class); assertIsMultipartRequest(servletRequest); MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class); Class<?> paramType = parameter.getParameterType(); boolean optional = paramType.getName().equals("java.util.Optional"); if (optional) { parameter.increaseNestingLevel(); paramType = parameter.getNestedParameterType(); } String partName = getPartName(parameter); Object arg; if (MultipartFile.class == paramType) { Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?"); arg = multipartRequest.getFile(partName); } else if (isMultipartFileCollection(parameter)) { Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?"); arg = multipartRequest.getFiles(partName); } else if (isMultipartFileArray(parameter)) { Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?"); List<MultipartFile> files = multipartRequest.getFiles(partName); arg = files.toArray(new MultipartFile[files.size()]); } else if ("javax.servlet.http.Part".equals(paramType.getName())) { assertIsMultipartRequest(servletRequest); arg = servletRequest.getPart(partName); } else if (isPartCollection(parameter)) { assertIsMultipartRequest(servletRequest); arg = new ArrayList<Object>(servletRequest.getParts()); } else if (isPartArray(parameter)) { assertIsMultipartRequest(servletRequest); arg = RequestPartResolver.resolvePart(servletRequest); } else { try { HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, partName); arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType()); WebDataBinder binder = binderFactory.createBinder(request, arg, partName); if (arg != null) { validateIfApplicable(binder, parameter); if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) { throw new MethodArgumentNotValidException(parameter, binder.getBindingResult()); } } mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult()); } catch (MissingServletRequestPartException ex) { // handled below arg = null; } } RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class); boolean isRequired = ((requestPart == null || requestPart.required()) && !optional); if (arg == null && isRequired) { throw new MissingServletRequestPartException(partName); } if (optional) { arg = Optional.ofNullable(arg); } return arg; }
@Test public void missingServletRequestPart() { Exception ex = new MissingServletRequestPartException("partName"); testException(ex); }
@ExceptionHandler({NoSuchRequestHandlingMethodException.class, HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class, MissingServletRequestParameterException.class, ServletRequestBindingException.class, ConversionNotSupportedException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, HttpMessageNotWritableException.class, MethodArgumentNotValidException.class, MissingServletRequestPartException.class, BindException.class, NoHandlerFoundException.class}) public final ResponseEntity<Object> handleException(Exception ex, HttpServletRequest request) { HttpHeaders headers = new HttpHeaders(); HttpStatus status; if(ex instanceof NoSuchRequestHandlingMethodException) { status = HttpStatus.NOT_FOUND; return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException)ex, headers, status, request); } else if(ex instanceof HttpRequestMethodNotSupportedException) { status = HttpStatus.METHOD_NOT_ALLOWED; return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException)ex, headers, status, request); } else if(ex instanceof HttpMediaTypeNotSupportedException) { status = HttpStatus.UNSUPPORTED_MEDIA_TYPE; return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException)ex, headers, status, request); } else if(ex instanceof HttpMediaTypeNotAcceptableException) { status = HttpStatus.NOT_ACCEPTABLE; return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException)ex, headers, status, request); } else if(ex instanceof MissingServletRequestParameterException) { status = HttpStatus.BAD_REQUEST; return handleMissingServletRequestParameter((MissingServletRequestParameterException)ex, headers, status, request); } else if(ex instanceof ServletRequestBindingException) { status = HttpStatus.BAD_REQUEST; return handleServletRequestBindingException((ServletRequestBindingException)ex, headers, status, request); } else if(ex instanceof ConversionNotSupportedException) { status = HttpStatus.INTERNAL_SERVER_ERROR; return handleConversionNotSupported((ConversionNotSupportedException)ex, headers, status, request); } else if(ex instanceof TypeMismatchException) { status = HttpStatus.BAD_REQUEST; return handleTypeMismatch((TypeMismatchException)ex, headers, status, request); } else if(ex instanceof HttpMessageNotReadableException) { status = HttpStatus.BAD_REQUEST; return handleHttpMessageNotReadable((HttpMessageNotReadableException)ex, headers, status, request); } else if(ex instanceof HttpMessageNotWritableException) { status = HttpStatus.INTERNAL_SERVER_ERROR; return handleHttpMessageNotWritable((HttpMessageNotWritableException)ex, headers, status, request); } else if(ex instanceof MethodArgumentNotValidException) { status = HttpStatus.BAD_REQUEST; return handleMethodArgumentNotValid((MethodArgumentNotValidException)ex, headers, status, request); } else if(ex instanceof MissingServletRequestPartException) { status = HttpStatus.BAD_REQUEST; return handleMissingServletRequestPart((MissingServletRequestPartException)ex, headers, status, request); } else if(ex instanceof BindException) { status = HttpStatus.BAD_REQUEST; return handleBindingResult(((BindException) ex).getBindingResult(), (BindException)ex, null, headers, status, request); } else if(ex instanceof NoHandlerFoundException) { status = HttpStatus.NOT_FOUND; return handleNoHandlerFoundException((NoHandlerFoundException)ex, headers, status, request); } else { logger.warn("Unknown exception type: " + ex.getClass().getName()); status = HttpStatus.INTERNAL_SERVER_ERROR; return handleExceptionInternal(ex, (Object)null, headers, status, request); } }
protected ResponseEntity<Object> handleMissingServletRequestPart(MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, HttpServletRequest request) { return handleExceptionInternal(ex, (Object) null, headers, status, request); }
@Override protected ModelAndView handleMissingServletRequestPartException(MissingServletRequestPartException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { return handleCustomException(request, response, ex); }
@ExceptionHandler default ResponseEntity<Problem> handleMissingServletRequestPart( final MissingServletRequestPartException exception, final NativeWebRequest request) { return create(Status.BAD_REQUEST, exception, request); }
@Override protected ModelAndView handleMissingServletRequestPartException(MissingServletRequestPartException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { super.handleMissingServletRequestPartException(ex, request, response, handler); return handleBadRequest(ex, request, response); }
@Override protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { try { if (ex instanceof NoSuchRequestHandlingMethodException) { return handleNoSuchRequestHandlingMethod((NoSuchRequestHandlingMethodException) ex, request, response, handler); } else if (ex instanceof HttpRequestMethodNotSupportedException) { return handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException) ex, request, response, handler); } else if (ex instanceof HttpMediaTypeNotSupportedException) { return handleHttpMediaTypeNotSupported((HttpMediaTypeNotSupportedException) ex, request, response, handler); } else if (ex instanceof HttpMediaTypeNotAcceptableException) { return handleHttpMediaTypeNotAcceptable((HttpMediaTypeNotAcceptableException) ex, request, response, handler); } else if (ex instanceof MissingServletRequestParameterException) { return handleMissingServletRequestParameter((MissingServletRequestParameterException) ex, request, response, handler); } else if (ex instanceof ServletRequestBindingException) { return handleServletRequestBindingException((ServletRequestBindingException) ex, request, response, handler); } else if (ex instanceof ConversionNotSupportedException) { return handleConversionNotSupported((ConversionNotSupportedException) ex, request, response, handler); } else if (ex instanceof TypeMismatchException) { return handleTypeMismatch((TypeMismatchException) ex, request, response, handler); } else if (ex instanceof HttpMessageNotReadableException) { return handleHttpMessageNotReadable((HttpMessageNotReadableException) ex, request, response, handler); } else if (ex instanceof HttpMessageNotWritableException) { return handleHttpMessageNotWritable((HttpMessageNotWritableException) ex, request, response, handler); } else if (ex instanceof MethodArgumentNotValidException) { return handleMethodArgumentNotValidException((MethodArgumentNotValidException) ex, request, response, handler); } else if (ex instanceof MissingServletRequestPartException) { return handleMissingServletRequestPartException((MissingServletRequestPartException) ex, request, response, handler); } else if (ex instanceof BindException) { return handleBindException((BindException) ex, request, response, handler); } } catch (Exception handlerException) { logger.warn("Handling of [" + ex.getClass().getName() + "] resulted in Exception", handlerException); } return null; }
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception { HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class); assertIsMultipartRequest(servletRequest); MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class); String partName = getPartName(parameter); Object arg; if (MultipartFile.class.equals(parameter.getParameterType())) { Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?"); arg = multipartRequest.getFile(partName); } else if (isMultipartFileCollection(parameter)) { Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?"); arg = multipartRequest.getFiles(partName); } else if ("javax.servlet.http.Part".equals(parameter.getParameterType().getName())) { arg = servletRequest.getPart(partName); } else { try { HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, partName); arg = readWithMessageConverters(inputMessage, parameter, parameter.getParameterType()); WebDataBinder binder = binderFactory.createBinder(request, arg, partName); if (arg != null) { validate(binder, parameter); } mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult()); } catch (MissingServletRequestPartException ex) { // handled below arg = null; } } RequestPart annot = parameter.getParameterAnnotation(RequestPart.class); boolean isRequired = (annot == null || annot.required()); if (arg == null && isRequired) { throw new MissingServletRequestPartException(partName); } return arg; }
@ExceptionHandler({ HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class, HttpMediaTypeNotAcceptableException.class, MissingPathVariableException.class, MissingServletRequestParameterException.class, ServletRequestBindingException.class, ConversionNotSupportedException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, HttpMessageNotWritableException.class, MethodArgumentNotValidException.class, MissingServletRequestPartException.class, BindException.class, AsyncRequestTimeoutException.class }) public final Object handleSpringException(Exception ex, HandlerMethod handlerMethod) { HttpStatus status; if (ex instanceof HttpRequestMethodNotSupportedException) { status = HttpStatus.METHOD_NOT_ALLOWED; return handleException(ex, handlerMethod, status, null); } else if (ex instanceof HttpMediaTypeNotSupportedException) { status = HttpStatus.UNSUPPORTED_MEDIA_TYPE; return handleException(ex, handlerMethod, status, null); } else if (ex instanceof HttpMediaTypeNotAcceptableException) { status = HttpStatus.NOT_ACCEPTABLE; return handleException(ex, handlerMethod, status, null); } else if (ex instanceof MissingPathVariableException || ex instanceof ConversionNotSupportedException || ex instanceof HttpMessageNotWritableException) { status = HttpStatus.INTERNAL_SERVER_ERROR; return handleException(ex, handlerMethod, status, null); } else if (ex instanceof MissingServletRequestParameterException || ex instanceof ServletRequestBindingException || ex instanceof TypeMismatchException || ex instanceof HttpMessageNotReadableException || ex instanceof MethodArgumentNotValidException || ex instanceof MissingServletRequestPartException || ex instanceof BindException) { status = HttpStatus.BAD_REQUEST; return handleException(ex, handlerMethod, status, null); } else if (ex instanceof AsyncRequestTimeoutException) { status = HttpStatus.SERVICE_UNAVAILABLE; return handleException(ex, handlerMethod, status, null); } else { if (LOG.isWarnEnabled()) { LOG.warn("Unknown exception type: " + ex.getClass().getName()); } status = HttpStatus.INTERNAL_SERVER_ERROR; return handleException(ex, handlerMethod, status, null); } }
/** * Handle the case where an {@linkplain RequestPart @RequestPart}, a {@link MultipartFile}, * or a {@code javax.servlet.http.Part} argument is required but is missing. * An HTTP 400 error is sent back to the client. * @param request current HTTP request * @param response current HTTP response * @param handler the executed handler * @return an empty ModelAndView indicating the exception was handled * @throws IOException potentially thrown from response.sendError() */ protected ModelAndView handleMissingServletRequestPartException(MissingServletRequestPartException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { response.sendError(HttpServletResponse.SC_BAD_REQUEST, ex.getMessage()); return new ModelAndView(); }
/** * Customize the response for MissingServletRequestPartException. * <p>This method delegates to {@link #handleExceptionInternal}. * @param ex the exception * @param headers the headers to be written to the response * @param status the selected response status * @param request the current request * @return a {@code ResponseEntity} instance */ protected ResponseEntity<Object> handleMissingServletRequestPart(MissingServletRequestPartException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); }