org.springframework.web.method.annotation.MethodArgumentTypeMismatchException Java Examples

The following examples show how to use org.springframework.web.method.annotation.MethodArgumentTypeMismatchException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseExceptionHandler.java    From controller-advice-exception-handler with MIT License 6 votes vote down vote up
public BaseExceptionHandler(final Logger log) {
    this.log = log;

    registerMapping(
            MissingServletRequestParameterException.class,
            "MISSING_PARAMETER",
            "Missing request parameter",
            BAD_REQUEST);
    registerMapping(
            MethodArgumentTypeMismatchException.class,
            "ARGUMENT_TYPE_MISMATCH",
            "Argument type mismatch",
            BAD_REQUEST);
    registerMapping(
            HttpRequestMethodNotSupportedException.class,
            "METHOD_NOT_SUPPORTED",
            "HTTP method not supported",
            METHOD_NOT_ALLOWED);
    registerMapping(
            ServletRequestBindingException.class,
            "MISSING_HEADER",
            "Missing header in request",
            BAD_REQUEST);
}
 
Example #2
Source File: RestControllerAdvice.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
/**
 * Client did not formulate a correct request.
 * Log the exception message at warn level and stack trace as trace level.
 * Return response status HttpStatus.BAD_REQUEST (400).
 */
@ExceptionHandler({
	MissingServletRequestParameterException.class,
	MethodArgumentTypeMismatchException.class,
	InvalidStreamDefinitionException.class
})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public VndErrors onClientGenericBadRequest(Exception e) {
	String logref = logWarnLevelExceptionMessage(e);
	if (logger.isTraceEnabled()) {
		logTraceLevelStrackTrace(e);
	}
	String msg = getExceptionMessage(e);
	return new VndErrors(logref, msg);
}
 
Example #3
Source File: GlobalExceptionTranslator.java    From staffjoy with MIT License 6 votes vote down vote up
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public BaseResponse handleError(MethodArgumentTypeMismatchException e) {
    logger.warn("Method Argument Type Mismatch", e);
    String message = String.format("Method Argument Type Mismatch: %s", e.getName());
    return BaseResponse
            .builder()
            .code(ResultCode.PARAM_TYPE_ERROR)
            .message(message)
            .build();
}
 
Example #4
Source File: ExceptionHandleController.java    From OneBlog with GNU General Public License v3.0 5 votes vote down vote up
/**
 * MethodArgumentTypeMismatchException : 方法参数类型异常
 *
 * @param e
 * @return
 */
@ExceptionHandler(value = MethodArgumentTypeMismatchException.class)
@ResponseBody
public Object methodArgumentTypeMismatchException(Throwable e) {
    log.error("url参数异常,请检查参数类型是否匹配!", e);
    if (RequestUtil.isAjax(RequestHolder.getRequest())) {
        return ResultUtil.error(ResponseStatus.INVALID_PARAMS);
    }
    return ResultUtil.forward("/error/500");
}
 
Example #5
Source File: CustomRestExceptionHandler.java    From tutorials with MIT License 5 votes vote down vote up
@ExceptionHandler({ MethodArgumentTypeMismatchException.class })
public ResponseEntity<Object> handleMethodArgumentTypeMismatch(final MethodArgumentTypeMismatchException ex, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getName() + " should be of type " + ex.getRequiredType().getName();

    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example #6
Source File: ExceptionHandlers.java    From studio with GNU General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseBody handleMethodArgumentTypeMismatchException(HttpServletRequest request,
                                                              MethodArgumentTypeMismatchException e) {
    ApiResponse response = new ApiResponse(ApiResponse.INVALID_PARAMS);
    return handleExceptionInternal(request, e, response);
}
 
Example #7
Source File: RestExceptionHandler.java    From POC with Apache License 2.0 5 votes vote down vote up
/**
 * Handle Exception, handle generic Exception.class.
 * @param ex the Exception
 * @return the ApiError object
 * @param request a {@link org.springframework.web.context.request.WebRequest} object.
 */
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex,
		WebRequest request) {
	final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST);
	apiError.setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'",
			ex.getName(), ex.getValue(), Objects.requireNonNull(ex.getRequiredType()).getSimpleName()));
	apiError.setDebugMessage(ex.getMessage());
	return buildResponseEntity(apiError);
}
 
Example #8
Source File: BaseExceptionHandler.java    From controller-advice-exception-handler with MIT License 5 votes vote down vote up
public BaseExceptionHandler(final Logger log) {
    this.log = log;

    registerMapping(MissingServletRequestParameterException.class, "MISSING_PARAMETER", "Missing request parameter", BAD_REQUEST);
    registerMapping(MethodArgumentTypeMismatchException.class, "ARGUMENT_TYPE_MISMATCH", "Argument type mismatch", BAD_REQUEST);
    registerMapping(HttpRequestMethodNotSupportedException.class, "METHOD_NOT_SUPPORTED", "HTTP method not supported", METHOD_NOT_ALLOWED);
    registerMapping(ServletRequestBindingException.class, "MISSING_HEADER", "Missing header in request", BAD_REQUEST);
}
 
Example #9
Source File: OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void extractPropertyName_works_for_MethodArgumentTypeMismatchException() {
    // given
    MethodArgumentTypeMismatchException exMock = mock(MethodArgumentTypeMismatchException.class);
    String name = UUID.randomUUID().toString();
    doReturn(name).when(exMock).getName();

    // when
    String result = listener.extractPropertyName(exMock);

    // then
    assertThat(result).isEqualTo(name);
}
 
Example #10
Source File: OneOffSpringCommonFrameworkExceptionHandlerListener.java    From backstopper with Apache License 2.0 5 votes vote down vote up
protected String extractPropertyName(TypeMismatchException tme) {
    if (tme instanceof MethodArgumentTypeMismatchException) {
        return ((MethodArgumentTypeMismatchException) tme).getName();
    }

    if (tme instanceof MethodArgumentConversionNotSupportedException) {
        return ((MethodArgumentConversionNotSupportedException) tme).getName();
    }

    return null;
}
 
Example #11
Source File: RestExceptionHandler.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Handle Exception, handle generic Exception.class
 *
 * @param ex the Exception
 * @return the ApiError object
 */
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex,
                                                                  WebRequest request) {
    RestApiError apiError = new RestApiError(BAD_REQUEST);
    apiError.setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'", ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName()));
    apiError.setDebugMessage(ex.getMessage());
    return buildResponseEntity(apiError);
}
 
Example #12
Source File: CustomRestExceptionHandler.java    From xxproject with Apache License 2.0 5 votes vote down vote up
@ExceptionHandler({ MethodArgumentTypeMismatchException.class })
public ResponseEntity<Object> handleMethodArgumentTypeMismatch(final MethodArgumentTypeMismatchException ex, final WebRequest request) {
    logger.info(ex.getClass().getName());
    //
    final String error = ex.getName() + " should be of type " + ex.getRequiredType().getName();

    final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error);
    return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
 
Example #13
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse handlerException(Exception e) {
    if (e instanceof NoHandlerFoundException) {
        log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
        return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
        return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD);
    } else if (e instanceof MethodArgumentNotValidException) {
        log.error("【全局异常拦截】MethodArgumentNotValidException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage(), null);
    } else if (e instanceof ConstraintViolationException) {
        log.error("【全局异常拦截】ConstraintViolationException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations())
                .getMessage(), null);
    } else if (e instanceof MethodArgumentTypeMismatchException) {
        log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
    } else if (e instanceof HttpMessageNotReadableException) {
        log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_NULL);
    } else if (e instanceof BadCredentialsException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR);
    } else if (e instanceof DisabledException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USER_DISABLED);
    } else if (e instanceof BaseException) {
        log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return ApiResponse.ofException((BaseException) e);
    }

    log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
    return ApiResponse.ofStatus(Status.ERROR);
}
 
Example #14
Source File: RestExceptionHandler.java    From spring-boot-exception-handling with MIT License 5 votes vote down vote up
/**
 * Handle Exception, handle generic Exception.class
 *
 * @param ex the Exception
 * @return the ApiError object
 */
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex,
                                                                  WebRequest request) {
    ApiError apiError = new ApiError(BAD_REQUEST);
    apiError.setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'", ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName()));
    apiError.setDebugMessage(ex.getMessage());
    return buildResponseEntity(apiError);
}
 
Example #15
Source File: BladeRestExceptionTranslator.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public R handleError(MethodArgumentTypeMismatchException e) {
	log.warn("请求参数格式错误", e.getMessage());
	String message = String.format("请求参数格式错误: %s", e.getName());
	return R.fail(ResultCode.PARAM_TYPE_ERROR, message);
}
 
Example #16
Source File: RestExceptionHandler.java    From spring-glee-o-meter with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Handle Exception, handle generic Exception.class
 *
 * @param ex the Exception
 * @return the ApiError object
 */
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex,
                                                                  WebRequest request) {
    ApiError apiError = new ApiError(BAD_REQUEST);
    apiError.setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'", ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName()));
    apiError.setDebugMessage(ex.getMessage());
    return buildResponseEntity(apiError);
}
 
Example #17
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse handlerException(Exception e) {
    if (e instanceof NoHandlerFoundException) {
        log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
        return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
        return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD);
    } else if (e instanceof MethodArgumentNotValidException) {
        log.error("【全局异常拦截】MethodArgumentNotValidException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage(), null);
    } else if (e instanceof ConstraintViolationException) {
        log.error("【全局异常拦截】ConstraintViolationException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations())
                .getMessage(), null);
    } else if (e instanceof MethodArgumentTypeMismatchException) {
        log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
    } else if (e instanceof HttpMessageNotReadableException) {
        log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_NULL);
    } else if (e instanceof BadCredentialsException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR);
    } else if (e instanceof DisabledException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USER_DISABLED);
    } else if (e instanceof BaseException) {
        log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return ApiResponse.ofException((BaseException) e);
    }

    log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
    return ApiResponse.ofStatus(Status.ERROR);
}
 
Example #18
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse handlerException(Exception e) {
    if (e instanceof NoHandlerFoundException) {
        log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
        return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
        return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD);
    } else if (e instanceof MethodArgumentNotValidException) {
        log.error("【全局异常拦截】MethodArgumentNotValidException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage(), null);
    } else if (e instanceof ConstraintViolationException) {
        log.error("【全局异常拦截】ConstraintViolationException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations())
                .getMessage(), null);
    } else if (e instanceof MethodArgumentTypeMismatchException) {
        log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
    } else if (e instanceof HttpMessageNotReadableException) {
        log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_NULL);
    } else if (e instanceof BadCredentialsException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR);
    } else if (e instanceof DisabledException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USER_DISABLED);
    } else if (e instanceof BaseException) {
        log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return ApiResponse.ofException((BaseException) e);
    }

    log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
    return ApiResponse.ofStatus(Status.ERROR);
}
 
Example #19
Source File: RestExceptionHandler.java    From spring-boot-akka-event-sourcing-starter with Apache License 2.0 5 votes vote down vote up
/**
 * Handle Exception, handle generic Exception.class
 *
 * @param ex the Exception
 * @return the ApiError object
 */
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
protected ResponseEntity<Object> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex,
                                                                  WebRequest request) {
	ApiError apiError = new ApiError(BAD_REQUEST);
	apiError.setMessage(String.format("The parameter '%s' of value '%s' could not be converted to type '%s'", ex.getName(), ex.getValue(), ex.getRequiredType().getSimpleName()));
	apiError.setDebugMessage(ex.getMessage());
	return buildResponseEntity(apiError);
}
 
Example #20
Source File: RestControllerExceptionHandler.java    From Spring-Boot-Blog-REST-API with GNU Affero General Public License v3.0 5 votes vote down vote up
@ExceptionHandler({ MethodArgumentTypeMismatchException.class })
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<ExceptionResponse> resolveException(MethodArgumentTypeMismatchException ex) {
	String message = "Parameter '" + ex.getParameter().getParameterName() + "' must be '"
			+ Objects.requireNonNull(ex.getRequiredType()).getSimpleName() + "'";
	List<String> messages = new ArrayList<>(1);
	messages.add(message);
	return new ResponseEntity<>(new ExceptionResponse(messages, HttpStatus.BAD_REQUEST.getReasonPhrase(),
			HttpStatus.BAD_REQUEST.value()), HttpStatus.BAD_REQUEST);
}
 
Example #21
Source File: GlobalExceptionHandler.java    From cola-cloud with MIT License 5 votes vote down vote up
@ResponseBody
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.OK)
public Result handleMethodArgumentTypeMismatchExceptionException(
        MethodArgumentTypeMismatchException e) {

    log.error(ErrorStatus.ILLEGAL_ARGUMENT_TYPE.getMessage() + ":" + e.getMessage());
    return failure(ErrorStatus.ILLEGAL_ARGUMENT_TYPE,e);
}
 
Example #22
Source File: GlobalExceptionHandler.java    From dk-foundation with GNU Lesser General Public License v2.1 5 votes vote down vote up
@ExceptionHandler({MethodArgumentTypeMismatchException.class})
public @ResponseBody
StandResponse exception(MethodArgumentTypeMismatchException e, HttpServletResponse response) {
    logger.error("#######ERROR#######", e);
    StandResponse standResponse = new StandResponse();
    standResponse.setCode(StandResponse.ARGUMENT_TYPE_MISSMATCH);
    standResponse.setSuccess(false);
    standResponse.setMsg("参数类型不匹配:" + e.getName());
    return standResponse;
}
 
Example #23
Source File: ErrorController.java    From kakaopay-coupon with MIT License 5 votes vote down vote up
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseBody
public ErrorInfo handleArgumentTypeMismatch(HttpServletRequest req, Exception ex) {
    log.info("handleArgumentTypeMismatch - Argument type mismatch");
    return new ErrorInfo(req.getRequestURL().toString(), "Argument type mismatch", ARG_TYPE_MISMATCH);
}
 
Example #24
Source File: GlobalExceptionHandler.java    From litemall with MIT License 4 votes vote down vote up
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseBody
public Object badArgumentHandler(MethodArgumentTypeMismatchException e) {
    logger.error(e.getMessage(), e);
    return ResponseUtil.badArgumentValue();
}
 
Example #25
Source File: TypeMismatchWebErrorHandler.java    From errors-spring-boot-starter with Apache License 2.0 4 votes vote down vote up
private static String getPropertyName(TypeMismatchException mismatchException) {
    if (mismatchException instanceof MethodArgumentTypeMismatchException)
        return ((MethodArgumentTypeMismatchException) mismatchException).getName();

    return mismatchException.getPropertyName();
}
 
Example #26
Source File: WebExceptionHandler.java    From jigsaw-payment with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseBody
public String processArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
	return ex.getMessage();
}
 
Example #27
Source File: OneOffSpringCommonFrameworkExceptionHandlerListener.java    From backstopper with Apache License 2.0 4 votes vote down vote up
protected ApiExceptionHandlerListenerResult handleTypeMismatchException(
    TypeMismatchException ex,
    List<Pair<String, String>> extraDetailsForLogging,
    boolean addBaseExceptionMessageToLoggingDetails
) {
    // The metadata will only be used if it's a 400 error.
    Map<String, Object> metadata = new LinkedHashMap<>();

    if (addBaseExceptionMessageToLoggingDetails) {
        utils.addBaseExceptionMessageToExtraDetailsForLogging(ex, extraDetailsForLogging);
    }

    String badPropName = extractPropertyName(ex);
    if (badPropName == null) {
        badPropName = ex.getPropertyName();
    }
    String badPropValue = (ex.getValue() == null) ? null : String.valueOf(ex.getValue());
    String requiredTypeNoInfoLeak = extractRequiredTypeNoInfoLeak(ex);

    extraDetailsForLogging.add(Pair.of("bad_property_name", badPropName));
    if (badPropName != null) {
        metadata.put("bad_property_name", badPropName);
    }
    extraDetailsForLogging.add(Pair.of("bad_property_value", String.valueOf(ex.getValue())));
    if (badPropValue != null) {
        metadata.put("bad_property_value", badPropValue);
    }
    extraDetailsForLogging.add(Pair.of("required_type", String.valueOf(ex.getRequiredType())));
    if (requiredTypeNoInfoLeak != null) {
        metadata.put("required_type", requiredTypeNoInfoLeak);
    }

    // ConversionNotSupportedException is a special case of TypeMismatchException that should be treated as
    //      a 500 internal service error. See Spring's DefaultHandlerExceptionResolver and/or
    //      ResponseEntityExceptionHandler for verification.
    if (ex instanceof ConversionNotSupportedException) {
        // We can add even more context log details if it's a MethodArgumentConversionNotSupportedException.
        if (ex instanceof MethodArgumentConversionNotSupportedException) {
            MethodArgumentConversionNotSupportedException macnsEx = (MethodArgumentConversionNotSupportedException)ex;
            extraDetailsForLogging.add(Pair.of("method_arg_name", macnsEx.getName()));
            extraDetailsForLogging.add(Pair.of("method_arg_target_param", macnsEx.getParameter().toString()));
        }

        return handleError(projectApiErrors.getGenericServiceError(), extraDetailsForLogging);
    }
    else {
        // All other TypeMismatchExceptions should be treated as a 400, and we can/should include the metadata.

        // We can add even more context log details if it's a MethodArgumentTypeMismatchException.
        if (ex instanceof MethodArgumentTypeMismatchException) {
            MethodArgumentTypeMismatchException matmEx = (MethodArgumentTypeMismatchException)ex;
            extraDetailsForLogging.add(Pair.of("method_arg_name", matmEx.getName()));
            extraDetailsForLogging.add(Pair.of("method_arg_target_param", matmEx.getParameter().toString()));
        }

        return handleError(
            new ApiErrorWithMetadata(projectApiErrors.getTypeConversionApiError(), metadata),
            extraDetailsForLogging
        );
    }
}
 
Example #28
Source File: GlobalExceptionHandler.java    From Dragonfly with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResultInfo handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
    return new ResultInfo(ResultCode.PARAM_ERROR, "invalid param", null);
}
 
Example #29
Source File: OneOffSpringCommonFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 4 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
})
@Test
public void shouldReturnTYPE_CONVERSION_ERRORForTypeMismatchException(
    boolean isMethodArgTypeMismatchEx
) {
    // given
    Object valueObj = "notAnInteger";
    Class<?> requiredType = Integer.class;
    Throwable someCause = new RuntimeException("some cause");
    String methodArgName = "fooArg";
    MethodParameter methodParam = mock(MethodParameter.class);

    TypeMismatchException ex =
        (isMethodArgTypeMismatchEx)
        ? new MethodArgumentTypeMismatchException(valueObj, requiredType, methodArgName, methodParam, someCause)
        : new TypeMismatchException(valueObj, requiredType, someCause);

    String expectedBadPropName = (isMethodArgTypeMismatchEx) ? methodArgName : null;

    List<Pair<String, String>> expectedExtraDetailsForLogging = new ArrayList<>(
        Arrays.asList(
            Pair.of("exception_message", ex.getMessage()),
            Pair.of("bad_property_name", expectedBadPropName),
            Pair.of("bad_property_value", String.valueOf(valueObj)),
            Pair.of("required_type", String.valueOf(requiredType))
        )
    );

    if (isMethodArgTypeMismatchEx) {
        expectedExtraDetailsForLogging.add(Pair.of("method_arg_name", methodArgName));
        expectedExtraDetailsForLogging.add(Pair.of("method_arg_target_param", methodParam.toString()));
    }

    Map<String, Object> expectedMetadata = MapBuilder
        .builder("bad_property_value", valueObj)
        .put("required_type", "int")
        .build();

    if (expectedBadPropName != null) {
        expectedMetadata.put("bad_property_name", expectedBadPropName);
    }

    // when
    ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex);

    // then
    validateResponse(result, true, singletonList(
        new ApiErrorWithMetadata(testProjectApiErrors.getTypeConversionApiError(), expectedMetadata)
    ));
    assertThat(result.extraDetailsForLogging).containsExactlyInAnyOrderElementsOf(expectedExtraDetailsForLogging);
}
 
Example #30
Source File: GlobalExceptionHandler.java    From mall with MIT License 4 votes vote down vote up
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseBody
public Object badArgumentHandler(MethodArgumentTypeMismatchException e) {
    e.printStackTrace();
    return ResponseUtil.badArgumentValue();
}