@ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public FieldErrorVM processMissingServletRequestParameterError(MissingServletRequestParameterException ex) { FieldErrorVM dto = new FieldErrorVM(ErrorConstants.ERR_VALIDATION, translate(ErrorConstants.ERR_VALIDATION)); dto.add(ex.getParameterType(), ex.getParameterName(), ex.getLocalizedMessage()); return dto; }
@ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public Map<String,String> paramMissErrorHandler(MissingServletRequestParameterException e) throws Exception { Map error = new HashMap(); error.put("error","参数" + e.getParameterName() + "不能为空"); return error; }
/** * 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); }
@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()); } }
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); }
/** * Test required parameter missing. */ @Test public void testRequiredParameterMissing() { RestAssured .registerParser("text/plain", Parser.TEXT); RestAssured .given() .param("radius", 0) .param("longitude", -1) .when() .get(RESTAURANT_API) .then() .statusCode(200) .body(Matchers.containsString(MissingServletRequestParameterException.class.toString())); }
/** * Test required parameter missing. */ @Test public void testRequiredParameterMissingAuthorizedCall() { User user = getUserWithUserTypeKunde(); userRepository.save(user); String authString = user.getUsername() + ":" + user.getPasswordconfirm(); byte[] base64Encoded = Base64.getEncoder().encode(authString.getBytes()); String encodedString = new String(base64Encoded); RestAssured .registerParser("text/plain", Parser.TEXT); RestAssured .given() .header("Authorization", "Basic " + encodedString) .param("radius", 0) .param("longitude", -1) .when() .get(RESTAURANT_API) .then() .statusCode(200) .body(Matchers.containsString(MissingServletRequestParameterException.class.toString())); }
@ExceptionHandler(Exception.class) public void handleUncaughtException(Exception ex, WebRequest request, HttpServletResponse response) throws IOException { if (ex instanceof HttpMediaTypeNotAcceptableException) { response.sendError(HttpStatus.NOT_ACCEPTABLE.value()); } else if (ex instanceof HttpMessageNotReadableException || ex instanceof MissingServletRequestParameterException || ex instanceof HttpMediaTypeNotSupportedException) { response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getLocalizedMessage().substring(0, ex.getLocalizedMessage().indexOf("\n"))); } else { int hashValue = response.hashCode(); //Note: we are giving the user a generic message. //Server logs can be used to troubleshoot problems. String msgText = "Something bad happened. Contact us with Reference Number: " + hashValue; LOG.error(msgText, ex); response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(), msgText); } }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // see if a handler is of the type that requires form context if (handler instanceof FormContextRequired) { FormContextRequired controller = (FormContextRequired)handler; try { Long formId = Long.valueOf(request.getParameter(FormContextRequired.FORM_ID_NAME)); controller.setFormId(formId); request.setAttribute(FormContextRequired.FORM_ID_NAME, formId); } catch (Exception e) { // either parameter is missing or invalid value throw new MissingServletRequestParameterException(FormContextRequired.FORM_ID_NAME, "Long"); } } return true; }
@Override protected ResponseEntity<Object> handleMissingServletRequestParameter(final MissingServletRequestParameterException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { logger.info(ex.getClass().getName()); // final String error = ex.getParameterName() + " parameter is missing"; final ApiError apiError = new ApiError(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error); return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus()); }
@ExceptionHandler(value = {IllegalArgumentException.class, BindException.class, // controller中参数绑定bean时异常,如数据类型不匹配等 MissingServletRequestParameterException.class, MethodArgumentTypeMismatchException.class, HttpRequestMethodNotSupportedException.class}) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody public Result handle400Error(HttpServletRequest req, Exception e) { String url = req.getMethod() + " " + req.getRequestURL() + "?" + req.getQueryString(); logger.debug("不合法的url请求: {}", url); ResultEnum badRequest = ResultEnum.BAD_REQUEST; return ResultUtils.error(badRequest.getCode(), badRequest.getMessage(), url); }
@Loggable @ResponseStatus(code = HttpStatus.CONFLICT) @ExceptionHandler(MissingServletRequestParameterException.class) public ErrorDto handleMissingServletRequestParameterError(MissingServletRequestParameterException ex) { return ErrorDto.builder() .errorCode(ErrorCodes.MISSING_REQUEST_PARAM) .errors(Collections.singleton(ex.getParameterName())) .message(ex.getLocalizedMessage()) .build(); }
@Override protected ResponseEntity<Object> handleMissingServletRequestParameter(final MissingServletRequestParameterException ex, final HttpHeaders headers, final HttpStatus status, final WebRequest request) { logger.info(ex.getClass().getName()); // final String error = ex.getParameterName() + " parameter is missing"; final AitException AitException = new AitException(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), error); return handleExceptionInternal(ex, AitException, headers, AitException.getStatus(), request); }
/** * 400 - Bad Request */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MissingServletRequestParameterException.class) public Response handleMissingServletRequestParameterException(MissingServletRequestParameterException e) { log.error("缺少请求参数: {}", e); return new Response().failure("required_parameter_is_not_present"); }
@ExceptionHandler(value = Exception.class) @ResponseBody public JsonData exceptionHandler(Exception ex) { if (ex instanceof IOException) return new JsonData<>(1, "IO异常", null); if (ex instanceof HttpRequestMethodNotSupportedException) return new JsonData<>(1,"您的访问方式有误",null); if (ex instanceof MissingServletRequestParameterException) return new JsonData<>(1,"请查看您的参数列表",null); return new JsonData<>(1, "未知异常", null); }
@ExceptionHandler({MissingServletRequestParameterException.class}) public ModelAndView processMissingServletRequestParameterException(NativeWebRequest request, MissingServletRequestParameterException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e.getMessage()); mv.setViewName("/common/error"); return mv; }
@ExceptionHandler({UnknownSessionException.class}) public ModelAndView processUnknownSessionException(NativeWebRequest request, MissingServletRequestParameterException e) { ModelAndView mv = new ModelAndView(); mv.addObject("exception", e.getMessage()); mv.setViewName("/signin"); return mv; }
public String getParameter(String paramName, String defaultValue) throws ServletException { String paramValue = request.getParameter(paramName); if (StringUtils.isEmpty(paramValue)) { if (defaultValue == null) { throw new MissingServletRequestParameterException(paramName, "String"); } else { return defaultValue; } } else { return paramValue; } }
@Test public void handleMissingServletRequestParameter() { MissingServletRequestParameterException ex = new MissingServletRequestParameterException("foo", "bar"); 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 bar parameter 'foo' is not present", response.getErrorMessage()); }
@Test public void shouldReturnMALFORMED_REQUESTForMissingServletRequestParameterException() { MissingServletRequestParameterException ex = new MissingServletRequestParameterException("someParam", "someParamType"); ApiExceptionHandlerListenerResult result = listener.shouldHandleException(ex); validateResponse(result, true, Collections.singletonList(testProjectApiErrors.getMalformedRequestApiError())); // Also should add base exception message to logging details. assertThat(result.extraDetailsForLogging.size(), is(1)); assertThat(result.extraDetailsForLogging.get(0), is(Pair.of("exception_message", "Required someParamType parameter 'someParam' is not present"))); }
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); }
@Parameterized.Parameters(name = "{index}:{0},{1},{2}") public static List<Object[]> getParameters() { return Arrays.asList(new Object[][] { { new ReportPortalException(EXCEPTION_MESSAGE), ErrorType.UNCLASSIFIED_REPORT_PORTAL_ERROR, HttpStatus.INTERNAL_SERVER_ERROR, EXCEPTION_MESSAGE }, { new RuntimeException(EXCEPTION_MESSAGE), ErrorType.UNCLASSIFIED_ERROR, HttpStatus.INTERNAL_SERVER_ERROR, EXCEPTION_MESSAGE }, { new HttpMessageNotReadableException(EXCEPTION_MESSAGE), ErrorType.INCORRECT_REQUEST, HttpStatus.BAD_REQUEST, EXCEPTION_MESSAGE }, { new MissingServletRequestParameterException("test", "test"), ErrorType.INCORRECT_REQUEST, HttpStatus.BAD_REQUEST, "Required test parameter 'test' is not present" } }); }
/** * 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). * * @param e one of the exceptions, {@link MissingServletRequestParameterException}, * {@link UnsatisfiedServletRequestParameterException}, * {@link MethodArgumentTypeMismatchException}, or * {@link InvalidStreamDefinitionException} * @return the error response in JSON format with media type * application/vnd.error+json */ @ExceptionHandler({ MissingServletRequestParameterException.class, HttpMessageNotReadableException.class, UnsatisfiedServletRequestParameterException.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); }
/** * Handle exceptions that result in a "bad request" status. */ @ExceptionHandler(value = {IllegalArgumentException.class, HttpMessageNotReadableException.class, MissingServletRequestParameterException.class, TypeMismatchException.class, UnsupportedEncodingException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public ErrorInformation handleBadRequestException(Exception exception) { return getErrorInformation(HttpStatus.BAD_REQUEST, exception); }
@Override protected ResponseEntity<Object> handleMissingServletRequestParameter( MissingServletRequestParameterException 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(MissingServletRequestParameterException.class) @ResponseStatus(BAD_REQUEST) @ResponseBody public ErrorsRepresentation handleMissingServletRequestParameterException(MissingServletRequestParameterException exception) { return conversionService.convert(exception, ErrorsRepresentation.class); }
/** * {@inheritDoc} * * Handle MissingServletRequestParameterException. Triggered when a 'required' request * parameter is missing. */ @Override protected ResponseEntity<Object> handleMissingServletRequestParameter( MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { final String error = ex.getParameterName() + " parameter is missing"; return buildResponseEntity(new ApiError(BAD_REQUEST, error, ex)); }
@ExceptionHandler(MissingServletRequestParameterException.class) public @ResponseBody ErrorWrapper handleMissingServletRequestParameterException(HttpServletRequest request, HttpServletResponse response, Exception ex) { ErrorWrapper errorWrapper = (ErrorWrapper) context.getBean(ErrorWrapper.class.getName()); Locale locale = null; String parameterType = null; String parameterName = null; BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext(); if (requestContext != null) { locale = requestContext.getJavaLocale(); } if (ex instanceof MissingServletRequestParameterException) { MissingServletRequestParameterException castedException = (MissingServletRequestParameterException)ex; parameterType = castedException.getParameterType(); parameterName = castedException.getParameterName(); } LOG.error("An error occured invoking a REST service", ex); if (locale == null) { locale = Locale.getDefault(); } if (parameterType == null) { parameterType = "String"; } if(parameterName == null) { parameterName = "[unknown name]"; } errorWrapper.setHttpStatusCode(HttpStatus.SC_BAD_REQUEST); response.setStatus(resolveResponseStatusCode(ex, errorWrapper)); ErrorMessageWrapper errorMessageWrapper = (ErrorMessageWrapper) context.getBean(ErrorMessageWrapper.class.getName()); errorMessageWrapper.setMessageKey(resolveClientMessageKey(BroadleafWebServicesException.QUERY_PARAMETER_NOT_PRESENT)); errorMessageWrapper.setMessage(messageSource.getMessage(BroadleafWebServicesException.QUERY_PARAMETER_NOT_PRESENT, new String[] {parameterType, parameterName}, BroadleafWebServicesException.QUERY_PARAMETER_NOT_PRESENT, locale)); errorWrapper.getMessages().add(errorMessageWrapper); return errorWrapper; }
/** * 处理MissingServletRequestParameterException异常的方法. * @param request - HttpRequest对象 * @param response - HttpResponse对象 * @return 返回一个包含异常信息的ModelAndView对象 */ @ResponseStatus(value=HttpStatus.BAD_REQUEST) @ExceptionHandler(MissingServletRequestParameterException.class) public ModelAndView badRequestView( HttpServletRequest request, HttpServletResponse response) { ModelAndView view = new ModelAndView("errors/404"); return view; }
@Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { String parameterName = parameter.getParameterName(); String parameterPayload = webRequest.getParameter(parameterName); if (parameterPayload == null) { DecodedUri methodAnnotation = findMethodAnnotation(DecodedUri.class, parameter); if (methodAnnotation.required()) { throw new MissingServletRequestParameterException(parameterName, "String"); } else { return null; } } return parseUri(parameterPayload); }
/** * 将spring中的http状态和异常互相对应 参考 spring的defaultExceptionHandler实现类似 * * @return */ private final Map<String, String> createDefaultExceptionMappingDefinitions() { Map<String, String> m = new LinkedHashMap<String, String>(); // 400 applyDef(m, HttpMessageNotReadableException.class, HttpStatus.BAD_REQUEST); applyDef(m, MissingServletRequestParameterException.class, HttpStatus.BAD_REQUEST); applyDef(m, TypeMismatchException.class, HttpStatus.BAD_REQUEST); applyDef(m, "javax.validation.ValidationException", HttpStatus.BAD_REQUEST); // 404 applyDef(m, NoSuchRequestHandlingMethodException.class, HttpStatus.NOT_FOUND); applyDef(m, "org.hibernate.ObjectNotFoundException", HttpStatus.NOT_FOUND); // 405 applyDef(m, HttpRequestMethodNotSupportedException.class, HttpStatus.METHOD_NOT_ALLOWED); // 406 applyDef(m, HttpMediaTypeNotAcceptableException.class, HttpStatus.NOT_ACCEPTABLE); // 409 applyDef(m, "org.springframework.dao.DataIntegrityViolationException", HttpStatus.CONFLICT); // 415 applyDef(m, HttpMediaTypeNotSupportedException.class, HttpStatus.UNSUPPORTED_MEDIA_TYPE); return m; }
@ExceptionHandler public ResponseEntity<RestApiErrorMessage> handleMissingKeyword( MissingServletRequestParameterException exception) { RestApiErrorMessage message = ErrorResponseFactory.createErrorMessage( MISSING_PARAMETER, exception.getParameterName()); return new ResponseEntity<RestApiErrorMessage>(message, MISSING_PARAMETER.getHttpStatus()); }
/** * {@link MissingServletRequestParameterException}をハンドリングします。 * @param e {@link MissingServletRequestParameterException} * @return {@link ErrorMessage} * HTTPステータス 400 でレスポンスを返却します。 */ @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseBody @ResponseStatus(value = HttpStatus.BAD_REQUEST) @Override public ErrorMessage handle(MissingServletRequestParameterException e) { if (L.isDebugEnabled()) { L.debug(R.getString("D-SPRINGMVC-REST-HANDLER#0005"), e); } ErrorMessage error = createClientErrorMessage(HttpStatus.BAD_REQUEST); warn(error, e); return error; }
@Test public void MissingServletRequestParameterExceptionをハンドリングできる() { MissingServletRequestParameterException ex = new MissingServletRequestParameterException("name", "type"); ErrorMessage message = this.exceptionHandlerSupport.handle(ex); assertThat(message, notNullValue()); assertThat(message.getStatus(), is(400)); assertThat(message.getMessage(), is("不正なリクエストです。")); }
@ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public void handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) { log.debug("A {} request for '{}' failed because parameter '{}' is missing.", request.getMethod(), request.getPathInfo(), e.getParameterName(), e); }
@RequestMapping(produces = {ApplicationMediaType.APPLICATION_BEARCHOKE_V1_JSON_VALUE, ApplicationMediaType.APPLICATION_BEARCHOKE_V2_JSON_VALUE}) @ExceptionHandler({MissingServletRequestParameterException.class, UnsatisfiedServletRequestParameterException.class, HttpRequestMethodNotSupportedException.class, ServletRequestBindingException.class }) @ResponseStatus(value = HttpStatus.BAD_REQUEST) public @ResponseBody ErrorMessage handleRequestException(Exception ex) { log.error("Http Status: " + HttpStatus.BAD_REQUEST + " : " + ex.getMessage(), ex); return new ErrorMessage(new Date(), HttpStatus.BAD_REQUEST.value(), ex.getClass().getName(), ex.getMessage()); }
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; }