/** * Gets properly typed method argument. * @param parameterType * @param value * @return */ private <T> T getMethodArgument(Class<T> parameterType, Object value) { if (parameterType.isInstance(value)) { return parameterType.cast(value); } try { return new SimpleTypeConverter().convertIfNecessary(value, parameterType); } catch (ConversionNotSupportedException e) { if (String.class.equals(parameterType)) { return (T) String.valueOf(value); } throw new ApplicationRuntimeException("Unable to convert method argument type", e); } }
/** * 500错误 */ @ResponseBody @ExceptionHandler({ ConversionNotSupportedException.class }) public ResultResponse ConversionNotSupportedExceptionHandler(ConversionNotSupportedException ex) { logger.error(ResultMessage.F5000.getMessage(), ex); return resultResponse.failure(ResultMessage.F5000); }
@Test public void handleConversionNotSupportedException() throws Exception { ConversionNotSupportedException ex = new ConversionNotSupportedException(new Object(), String.class, new Exception()); ModelAndView mav = exceptionResolver.resolveException(request, response, null, ex); assertNotNull("No ModelAndView returned", mav); assertTrue("No Empty ModelAndView returned", mav.isEmpty()); assertEquals("Invalid status code", 500, response.getStatus()); // SPR-9653 assertSame(ex, request.getAttribute("javax.servlet.error.exception")); }
public static void setFieldValue(Field field, Object bean, Object value) throws IllegalAccessException { // Set it on the field field.setAccessible(true); // Perform type conversion if possible.. SimpleTypeConverter converter = new SimpleTypeConverter(); try { value = converter.convertIfNecessary(value, field.getType()); } catch (ConversionNotSupportedException e) { // If conversion isn't supported, ignore and try and set anyway. } field.set(bean, value); }
@Override protected ResponseEntity<Object> handleConversionNotSupported( ConversionNotSupportedException 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 ); }
@ExceptionHandler({ NoSuchRequestHandlingMethodException.class, ConversionNotSupportedException.class }) @ResponseStatus(value = HttpStatus.NOT_FOUND) public String handleResourceNotFound(ModelMap model) { model.put("advancedSearchData", new SearchData()); return "resourceNotFound"; }
/** * {@link ConversionNotSupportedException}をハンドリングします。 * @param e {@link ConversionNotSupportedException} * @return {@link ErrorMessage} * HTTPステータス 500 でレスポンスを返却します。 */ @ExceptionHandler(ConversionNotSupportedException.class) @ResponseBody @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @Override public ErrorMessage handle(ConversionNotSupportedException e) { if (L.isDebugEnabled()) { L.debug(R.getString("D-SPRINGMVC-REST-HANDLER#0007"), e); } ErrorMessage error = createServerErrorMessage(HttpStatus.INTERNAL_SERVER_ERROR); error(error, e); return error; }
@Test public void ConversionNotSupportedExceptionをハンドリングできる() { ConversionNotSupportedException ex = new ConversionNotSupportedException(new Object(), Class.class, new Throwable()); ErrorMessage message = this.exceptionHandlerSupport.handle(ex); assertThat(message, notNullValue()); assertThat(message.getStatus(), is(500)); assertThat(message.getMessage(), is("予期しない例外が発生しました。")); }
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; }
@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; }
@Test public void conversionNotSupported() { Exception ex = new ConversionNotSupportedException(new Object(), Object.class, null); 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> handleConversionNotSupported(ConversionNotSupportedException ex, HttpHeaders headers, HttpStatus status, HttpServletRequest request) { return handleExceptionInternal(ex, (Object) null, headers, status, request); }
@Test public void testCopyList(){ Date now = new Date(); Date createTime = new Date(now.getTime()+3600000); String userName = "testName"; long id = 111333L; CapitalBean srcBean = new CapitalBean(); srcBean.setId(id); srcBean.setUserName(userName); srcBean.setBirthday(now); srcBean.setCreateTime(createTime); long dataId = 2342332; String subName = "subNameTest"; CapitalBean2 srcData = new CapitalBean2(); srcData.setId(dataId); srcData.setSubName(subName); srcData.setCreateTime(createTime); List<CapitalBean2> datas = new ArrayList<CopyUtilsTest.CapitalBean2>(); datas.add(srcData); srcBean.setDatas(datas); try { UnderlineBeanWithoutCloneable underlineBeanWithoutCloneable = CopyUtils.copy(UnderlineBeanWithoutCloneable.class, srcBean); Assert.fail("it should be faield"); } catch (Exception e) { Assert.assertTrue(ConversionNotSupportedException.class.isInstance(e)); } UnderlineBean target = CopyUtils.copy(UnderlineBean.class, srcBean); Assert.assertEquals(userName, target.getUser_name()); Assert.assertEquals(id, target.getId()); Assert.assertEquals(createTime, target.getCreate_time()); Assert.assertEquals(now, target.getBirthday()); Assert.assertEquals(srcBean.getId(), target.getId()); Assert.assertEquals(srcBean.getUserName(), target.getUser_name()); Assert.assertEquals(srcBean.getBirthday(), target.getBirthday()); Assert.assertEquals(srcBean.getCreateTime(), target.getCreate_time()); Assert.assertNotNull(target.getDatas()); Assert.assertEquals(1, target.getDatas().size()); UnderlineBean2 targetData = target.getDatas().get(0); Assert.assertEquals(dataId, targetData.getId()); Assert.assertEquals(subName, targetData.getSub_name()); Assert.assertEquals(createTime, targetData.getCreate_time()); srcBean = CopyUtils.copy(new CapitalBean(), target); Assert.assertEquals(userName, srcBean.getUserName()); Assert.assertEquals(id, srcBean.getId()); Assert.assertEquals(createTime, srcBean.getCreateTime()); Assert.assertEquals(now, srcBean.getBirthday()); Assert.assertEquals(srcBean.getId(), target.getId()); Assert.assertEquals(srcBean.getUserName(), target.getUser_name()); Assert.assertEquals(srcBean.getBirthday(), target.getBirthday()); Assert.assertEquals(srcBean.getCreateTime(), target.getCreate_time()); }
@Override protected ModelAndView handleConversionNotSupported(ConversionNotSupportedException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { super.handleConversionNotSupported(ex, request, response, handler); return contentNegotiatingModelAndView(createErrorResponse(request, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex)); }
@ExceptionHandler({ NoSuchRequestHandlingMethodException.class, ConversionNotSupportedException.class }) @ResponseStatus(value = HttpStatus.NOT_FOUND) public String handleResourceNotFound() { return "resourceNotFound"; }
@ExceptionHandler({NoSuchRequestHandlingMethodException.class, ConversionNotSupportedException.class}) @ResponseStatus(value = HttpStatus.NOT_FOUND) public String handleResourceNotFound(){ return "resourceNotFound"; }
@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; }
@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 when a {@link org.springframework.web.bind.WebDataBinder} conversion cannot occur. * <p>The default implementation sends an HTTP 500 error, and returns an empty {@code ModelAndView}. * Alternatively, a fallback view could be chosen, or the TypeMismatchException could be rethrown as-is. * @param ex the ConversionNotSupportedException to be handled * @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 handleConversionNotSupported(ConversionNotSupportedException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { if (logger.isWarnEnabled()) { logger.warn("Failed to convert request element: " + ex); } sendServerError(ex, request, response); return new ModelAndView(); }
/** * Handle the case when a {@link org.springframework.web.bind.WebDataBinder} conversion cannot occur. * <p>The default implementation sends an HTTP 500 error, and returns an empty {@code ModelAndView}. * Alternatively, a fallback view could be chosen, or the TypeMismatchException could be rethrown as-is. * @param ex the ConversionNotSupportedException to be handled * @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 handleConversionNotSupported(ConversionNotSupportedException ex, HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { sendServerError(ex, request, response); return new ModelAndView(); }
/** * Customize the response for ConversionNotSupportedException. * <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> handleConversionNotSupported(ConversionNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); }
/** * Customize the response for ConversionNotSupportedException. * This method delegates to {@link #handleExceptionInternal(Exception, Object, HttpHeaders, HttpStatus, WebRequest)}. * @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> handleConversionNotSupported(ConversionNotSupportedException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { return handleExceptionInternal(ex, null, headers, status, request); }
/** * {@link ConversionNotSupportedException}をハンドリングします。 * @param e {@link ConversionNotSupportedException} * @return 任意の型 */ T handle(ConversionNotSupportedException e);