org.springframework.web.HttpRequestMethodNotSupportedException Java Examples

The following examples show how to use org.springframework.web.HttpRequestMethodNotSupportedException. 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: DefaultAnnotationHandlerMapping.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the given type-level mapping metadata against the current request,
 * checking HTTP request method and parameter conditions.
 * @param mapping the mapping metadata to validate
 * @param request current HTTP request
 * @throws Exception if validation failed
 */
protected void validateMapping(RequestMapping mapping, HttpServletRequest request) throws Exception {
	RequestMethod[] mappedMethods = mapping.method();
	if (!ServletAnnotationMappingUtils.checkRequestMethod(mappedMethods, request)) {
		String[] supportedMethods = new String[mappedMethods.length];
		for (int i = 0; i < mappedMethods.length; i++) {
			supportedMethods[i] = mappedMethods[i].name();
		}
		throw new HttpRequestMethodNotSupportedException(request.getMethod(), supportedMethods);
	}

	String[] mappedParams = mapping.params();
	if (!ServletAnnotationMappingUtils.checkParameters(mappedParams, request)) {
		throw new UnsatisfiedServletRequestParameterException(mappedParams, request.getParameterMap());
	}

	String[] mappedHeaders = mapping.headers();
	if (!ServletAnnotationMappingUtils.checkHeaders(mappedHeaders, request)) {
		throw new ServletRequestBindingException("Header conditions \"" +
				StringUtils.arrayToDelimitedString(mappedHeaders, ", ") +
				"\" not met for actual request");
	}
}
 
Example #2
Source File: ExceptionControllerAdvice.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * @param
 * @return
 * @author GS
 * @description 错误请求方式异常  HttpRequestMethodNotSupportedException
 * @date 2018/2/28 17:32
 */
@ResponseBody
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public MessageResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
    ex.printStackTrace();
    log.info(">>>错误请求方式异常>>",ex);
    String methods = "";
    //支持的请求方式
    String[] supportedMethods = ex.getSupportedMethods();
    for (String method : supportedMethods) {
        methods += method;
    }
    MessageResult result = MessageResult.error("Request method " + ex.getMethod() + "  not supported !" +
            " supported method : " + methods + "!");
    return result;
}
 
Example #3
Source File: DefaultRestMsgHandler.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
@Override
public void process(PluginContext ctx, PluginRestMsg msg) {
  try {
    log.debug("[{}] Processing REST msg: {}", ctx.getPluginId(), msg);
    HttpMethod method = msg.getRequest().getMethod();
    switch (method) {
    case GET:
      handleHttpGetRequest(ctx, msg);
      break;
    case POST:
      handleHttpPostRequest(ctx, msg);
      break;
    case DELETE:
      handleHttpDeleteRequest(ctx, msg);
      break;
    default:
      msg.getResponseHolder().setErrorResult(new HttpRequestMethodNotSupportedException(method.name()));
    }
    log.debug("[{}] Processed REST msg.", ctx.getPluginId());
  } catch (Exception e) {
    log.warn("[{}] Exception during REST msg processing: {}", ctx.getPluginId(), e.getMessage(), e);
    msg.getResponseHolder().setErrorResult(e);
  }
}
 
Example #4
Source File: HttpRequestHandlerServlet.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	LocaleContextHolder.setLocale(request.getLocale());
	try {
		this.target.handleRequest(request, response);
	}
	catch (HttpRequestMethodNotSupportedException ex) {
		String[] supportedMethods = ex.getSupportedMethods();
		if (supportedMethods != null) {
			response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
		}
		response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example #5
Source File: JeecgBootExceptionHandler.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * @Author 政辉
 * @param e
 * @return
 */
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<?> HttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e){
	StringBuffer sb = new StringBuffer();
	sb.append("不支持");
	sb.append(e.getMethod());
	sb.append("请求方法,");
	sb.append("支持以下");
	String [] methods = e.getSupportedMethods();
	if(methods!=null){
		for(String str:methods){
			sb.append(str);
			sb.append("、");
		}
	}
	log.error(sb.toString(), e);
	//return Result.error("没有权限,请联系管理员授权");
	return Result.error(405,sb.toString());
}
 
Example #6
Source File: HttpRequestHandlerServlet.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	Assert.state(this.target != null, "No HttpRequestHandler available");

	LocaleContextHolder.setLocale(request.getLocale());
	try {
		this.target.handleRequest(request, response);
	}
	catch (HttpRequestMethodNotSupportedException ex) {
		String[] supportedMethods = ex.getSupportedMethods();
		if (supportedMethods != null) {
			response.setHeader("Allow", StringUtils.arrayToDelimitedString(supportedMethods, ", "));
		}
		response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, ex.getMessage());
	}
	finally {
		LocaleContextHolder.resetLocaleContext();
	}
}
 
Example #7
Source File: HessianServiceExporter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Processes the incoming Hessian request and creates a Hessian response.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (!"POST".equals(request.getMethod())) {
		throw new HttpRequestMethodNotSupportedException(request.getMethod(),
				new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
	}

	response.setContentType(CONTENT_TYPE_HESSIAN);
	try {
		invoke(request.getInputStream(), response.getOutputStream());
	}
	catch (Throwable ex) {
		throw new NestedServletException("Hessian skeleton invocation failed", ex);
	}
}
 
Example #8
Source File: RestExceptionHandler.java    From java-starthere with MIT License 6 votes vote down vote up
@Override
protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
                                                                     HttpHeaders headers,
                                                                     HttpStatus status,
                                                                     WebRequest request)
{
    ErrorDetail errorDetail = new ErrorDetail();
    errorDetail.setTimestamp(new Date().getTime());
    errorDetail.setStatus(HttpStatus.NOT_FOUND.value());
    errorDetail.setTitle(ex.getMethod());
    errorDetail.setDetail(request.getDescription(true));
    errorDetail.setDeveloperMessage("HTTP Method Not Valid for Endpoint (check for valid URI and proper HTTP Method)");

    return new ResponseEntity<>(errorDetail,
                                headers,
                                HttpStatus.NOT_FOUND);
}
 
Example #9
Source File: ExceptionControllerAdvice.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * @param
 * @return
 * @author GS
 * @description 错误请求方式异常  HttpRequestMethodNotSupportedException
 * @date 2018/2/28 17:32
 */
@ResponseBody
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
public MessageResult httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
    ex.printStackTrace();
    log.info(">>>错误请求方式异常>>",ex);
    String methods = "";
    //支持的请求方式
    String[] supportedMethods = ex.getSupportedMethods();
    for (String method : supportedMethods) {
        methods += method;
    }
    MessageResult result = MessageResult.error("Request method " + ex.getMethod() + "  not supported !" +
            " supported method : " + methods + "!");
    return result;
}
 
Example #10
Source File: LockingAndVersioningRestController.java    From spring-content with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(value = ENTITY_LOCK_MAPPING, method = RequestMethod.DELETE)
public ResponseEntity<Resource<?>> unlock(RootResourceInformation repoInfo,
										  @PathVariable String repository,
										  @PathVariable String id, Principal principal)
		throws ResourceNotFoundException, HttpRequestMethodNotSupportedException {

	Object domainObj = repoInfo.getInvoker().invokeFindById(id).get();

	domainObj = ReflectionUtils.invokeMethod(UNLOCK_METHOD, repositories.getRepositoryFor(domainObj.getClass()).get(), domainObj);

	if (domainObj != null) {
		return ResponseEntity.ok().build();
	} else {
		return ResponseEntity.status(HttpStatus.CONFLICT).build();
	}
}
 
Example #11
Source File: HessianServiceExporter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Processes the incoming Hessian request and creates a Hessian response.
 */
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {

	if (!"POST".equals(request.getMethod())) {
		throw new HttpRequestMethodNotSupportedException(request.getMethod(),
				new String[] {"POST"}, "HessianServiceExporter only supports POST requests");
	}

	response.setContentType(CONTENT_TYPE_HESSIAN);
	try {
	  invoke(request.getInputStream(), response.getOutputStream());
	}
	catch (Throwable ex) {
	  throw new NestedServletException("Hessian skeleton invocation failed", ex);
	}
}
 
Example #12
Source File: MethodNotAllowedAdviceTraitTest.java    From problem-spring-web with MIT License 5 votes vote down vote up
@Test
void noAllowIfNoneAllowed() {
    final MethodNotAllowedAdviceTrait unit = new MethodNotAllowedAdviceTrait() {
    };
    final ResponseEntity<Problem> entity = unit.handleRequestMethodNotSupportedException(
            new HttpRequestMethodNotSupportedException("non allowed", new String[]{}), mock(NativeWebRequest.class));

    assertThat(entity.getHeaders(), not(hasKey("Allow")));
}
 
Example #13
Source File: DefaultExceptionHandler.java    From ruoyiplus with MIT License 5 votes vote down vote up
/**
 * 请求方式不支持
 */
@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
public AjaxResult handleException(HttpRequestMethodNotSupportedException e)
{
    log.error(e.getMessage(), e);
    return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
}
 
Example #14
Source File: ExceptionHandlingController.java    From voj with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 处理HttpRequestMethodNotSupportedException异常的方法.
 * @param request - HttpRequest对象
 * @param response - HttpResponse对象
 * @return 返回一个包含异常信息的ModelAndView对象
 */
@ResponseStatus(value=HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public ModelAndView methodNotAllowedView(
		HttpServletRequest request, HttpServletResponse response) {
	ModelAndView view = new ModelAndView("errors/404");
	return view;
}
 
Example #15
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void getHandlerRequestMethodNotAllowed() throws Exception {
	try {
		MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar");
		this.handlerMapping.getHandler(request);
		fail("HttpRequestMethodNotSupportedException expected");
	}
	catch (HttpRequestMethodNotSupportedException ex) {
		assertArrayEquals("Invalid supported methods", new String[]{"GET", "HEAD"},
				ex.getSupportedMethods());
	}
}
 
Example #16
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 #17
Source File: GlobalExceptionHandler.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
/**
 * 405 - Method Not Allowed
 */
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Map<String, Object> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
    logger.error("不支持当前请求方法", e);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("rspCode", 405);
    map.put("rspMsg", e.getMessage());
    //发生异常进行日志记录,写入数据库或者其他处理,此处省略
    return map;
}
 
Example #18
Source File: ContentPropertyRestController.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@StoreType("contentstore")
@RequestMapping(value = BASE_MAPPING, method = RequestMethod.DELETE)
@ResponseBody
public ResponseEntity<?> deleteContent(@RequestHeader HttpHeaders headers,
									   @PathVariable String repository,
									   @PathVariable String id,
									   @PathVariable String contentProperty,
									   @PathVariable String contentId)
		throws HttpRequestMethodNotSupportedException {

	Object domainObj = findOne(repositories, repository, id);

	String etag = (BeanUtils.getFieldWithAnnotation(domainObj, Version.class) != null ? BeanUtils.getFieldWithAnnotation(domainObj, Version.class).toString() : null);
	Object lastModifiedDate = (BeanUtils.getFieldWithAnnotation(domainObj, LastModifiedDate.class) != null ? BeanUtils.getFieldWithAnnotation(domainObj, LastModifiedDate.class) : null);
	HeaderUtils.evaluateHeaderConditions(headers, etag, lastModifiedDate);

	PersistentProperty<?> property = this.getContentPropertyDefinition(
			repositories.getPersistentEntity(domainObj.getClass()), contentProperty);

	Object contentPropertyValue = getContentProperty(domainObj, property, contentId);

	Class<?> contentEntityClass = ContentPropertyUtils.getContentPropertyType(property);

	ContentStoreInfo info = ContentStoreUtils.findContentStore(storeService, contentEntityClass);

	info.getImpementation().unsetContent(contentPropertyValue);

	// remove the content property reference from the data object
	// setContentProperty(domainObj, property, contentId, null);

	save(repositories, domainObj);

	return new ResponseEntity<Object>(HttpStatus.NO_CONTENT);
}
 
Example #19
Source File: AbstractContentPropertyController.java    From spring-content with Apache License 2.0 5 votes vote down vote up
public static Iterable findAll(Repositories repositories, String repository)
		throws HttpRequestMethodNotSupportedException {

	Iterable entities = null;

	RepositoryInformation ri = RepositoryUtils.findRepositoryInformation(repositories, repository);

	if (ri == null) {
		throw new ResourceNotFoundException();
	}

	Class<?> domainObjClazz = ri.getDomainType();
	Class<?> idClazz = ri.getIdType();

	Optional<Method> findAllMethod = ri.getCrudMethods().getFindAllMethod();
	if (!findAllMethod.isPresent()) {
		throw new HttpRequestMethodNotSupportedException("fineAll");
	}

	entities = (Iterable) ReflectionUtils.invokeMethod(findAllMethod.get(),
			repositories.getRepositoryFor(domainObjClazz));

	if (null == entities) {
		throw new ResourceNotFoundException();
	}

	return entities;
}
 
Example #20
Source File: ExceptionHandling.java    From Tbed with GNU Affero General Public License v3.0 5 votes vote down vote up
@ExceptionHandler
public String test3(HttpRequestMethodNotSupportedException e,Model model){

    ModelAndView modelAndView = new ModelAndView("/index");
    Print.Normal("URL访问类型不正确:"+ e.getMessage());
    //e.printStackTrace();
    modelAndView.addObject("error","URL访问类型不正确。");
    model.addAttribute("error","URL访问类型不正确。");
    //返回错误信息,并显示给用户
    //return e.getMessage();
    return "exception";
}
 
Example #21
Source File: ExceptionTranslatorTest.java    From jhipster-registry with Apache License 2.0 5 votes vote down vote up
@Test
public void processMethodNotSupportedExceptionTest() throws Exception {
    MvcResult res = mock.perform(post("/api/account")
        .content("{\"testFakeParam\"}"))
        .andExpect(status().isMethodNotAllowed())
        .andReturn();

    assertThat(res.getResolvedException()).isInstanceOf(HttpRequestMethodNotSupportedException.class);
}
 
Example #22
Source File: ContentSearchRestController.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@StoreType("contentstore")
@RequestMapping(value = ENTITY_CONTENTSEARCH_MAPPING, method = RequestMethod.GET)
public ResponseEntity<?> searchContent(RootResourceInformation repoInfo,
		DefaultedPageable pageable,
		Sort sort,
		PersistentEntityResourceAssembler assembler,
		@PathVariable String repository,
		@RequestParam(name = "queryString") String queryString)
		throws HttpRequestMethodNotSupportedException {

	return searchContentInternal(repoInfo, pageable, sort, assembler, "search", new String[]{queryString});
}
 
Example #23
Source File: ResponseEntityExceptionHandlerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void httpRequestMethodNotSupported() {
	List<String> supported = Arrays.asList("POST", "DELETE");
	Exception ex = new HttpRequestMethodNotSupportedException("GET", supported);

	ResponseEntity<Object> responseEntity = testException(ex);
	assertEquals(EnumSet.of(HttpMethod.POST, HttpMethod.DELETE), responseEntity.getHeaders().getAllow());
}
 
Example #24
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void getHandlerRequestMethodNotAllowed() throws Exception {
	try {
		MockHttpServletRequest request = new MockHttpServletRequest("POST", "/bar");
		this.handlerMapping.getHandler(request);
		fail("HttpRequestMethodNotSupportedException expected");
	}
	catch (HttpRequestMethodNotSupportedException ex) {
		assertArrayEquals("Invalid supported methods", new String[]{"GET", "HEAD"},
				ex.getSupportedMethods());
	}
}
 
Example #25
Source File: GlobalDefaultExceptionHandler.java    From unified-dispose-springboot with Apache License 2.0 5 votes vote down vote up
/**
 * HttpRequestMethodNotSupportedException 405 异常处理
 */
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result handlerHttpRequestMethodNotSupportedException(
        HttpRequestMethodNotSupportedException e) throws Throwable {
    errorDispose(e);
    outPutErrorWarn(HttpRequestMethodNotSupportedException.class,
            CommonErrorCode.METHOD_NOT_ALLOWED, e);
    return Result.ofFail(CommonErrorCode.METHOD_NOT_ALLOWED);
}
 
Example #26
Source File: LockingAndVersioningRestController.java    From spring-content with Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = FINDALLVERSIONS_METHOD_MAPPING, method = RequestMethod.GET)
public ResponseEntity<?> findAllVersions(RootResourceInformation repoInfo,
										 PersistentEntityResourceAssembler assembler,
										 @PathVariable String repository,
										 @PathVariable String id)
		throws ResourceNotFoundException, HttpRequestMethodNotSupportedException {

	Object domainObj = repoInfo.getInvoker().invokeFindById(id).get();

	List result = (List)ReflectionUtils.invokeMethod(FINDALLVERSIONS_METHOD, repositories.getRepositoryFor(domainObj.getClass()).get(), domainObj);

	return ResponseEntity.ok(toResources(result, assembler, this.pagedResourcesAssembler, domainObj.getClass(), null));
}
 
Example #27
Source File: ResponseEntityExceptionHandler.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Customize the response for HttpRequestMethodNotSupportedException.
 * <p>This method logs a warning, sets the "Allow" header, and 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> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
		HttpHeaders headers, HttpStatus status, WebRequest request) {

	pageNotFoundLogger.warn(ex.getMessage());

	Set<HttpMethod> supportedMethods = ex.getSupportedHttpMethods();
	if (!supportedMethods.isEmpty()) {
		headers.setAllow(supportedMethods);
	}

	return handleExceptionInternal(ex, null, headers, status, request);
}
 
Example #28
Source File: OneOffSpringWebMvcFrameworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleException_returns_METHOD_NOT_ALLOWED_for_HttpRequestMethodNotSupportedException() {
    // given
    HttpRequestMethodNotSupportedException ex = new HttpRequestMethodNotSupportedException("asplode");

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

    // then
    validateResponse(result, true, singletonList(testProjectApiErrors.getMethodNotAllowedApiError()));
}
 
Example #29
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 #30
Source File: ServletWebErrorHandlerTest.java    From errors-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private Object[] provideParamsForCanHandle() {
    return p(
        p(null, false),
        p(new RuntimeException(), false),
        p(new NoHandlerFoundException(null, null, null), true),
        p(new HttpMessageNotReadableException("", mock(HttpInputMessage.class)), true),
        p(new MissingServletRequestParameterException("name", "String"), true),
        p(new HttpMediaTypeNotAcceptableException(""), true),
        p(new HttpMediaTypeNotSupportedException(""), true),
        p(new HttpRequestMethodNotSupportedException(""), true),
        p(new MissingServletRequestPartException("file"), true)
    );
}