org.springframework.cloud.gateway.support.NotFoundException Java Examples

The following examples show how to use org.springframework.cloud.gateway.support.NotFoundException. 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: GateWayExceptionHandlerAdvice.java    From JetfireCloud with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(value = {Throwable.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handle(Throwable throwable) {
    Result result = Result.fail();
    if (throwable instanceof ResponseStatusException) {
        result = handle((ResponseStatusException) throwable);
    } else if (throwable instanceof ConnectTimeoutException) {
        result = handle((ConnectTimeoutException) throwable);
    } else if (throwable instanceof NotFoundException) {
        result = handle((NotFoundException) throwable);
    } else if (throwable instanceof RuntimeException) {
        result = handle((RuntimeException) throwable);
    } else if (throwable instanceof Exception) {
        result = handle((Exception) throwable);
    }
    return result;
}
 
Example #2
Source File: SyncopeSRAWebExceptionHandler.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> handle(final ServerWebExchange exchange, final Throwable throwable) {
    if (throwable instanceof ConnectException
            || throwable instanceof NativeIoException
            || throwable instanceof NotFoundException) {

        LOG.error("ConnectException thrown", throwable);

        return doHandle(exchange, throwable, HttpStatus.NOT_FOUND);
    } else if (throwable instanceof OAuth2AuthorizationException) {
        LOG.error("OAuth2AuthorizationException thrown", throwable);

        return doHandle(exchange, throwable, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    return Mono.error(throwable);
}
 
Example #3
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldThrow4O4ExceptionWhenNoServiceInstanceIsFound() {
	URI uri = UriComponentsBuilder.fromUriString("lb://service1").build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);
	RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(
			ServiceInstanceListSuppliers.toProvider("service1"), "service1", -1);
	when(clientFactory.getInstance("service1", ReactorLoadBalancer.class,
			ServiceInstance.class)).thenReturn(loadBalancer);
	properties.setUse404(true);
	ReactiveLoadBalancerClientFilter filter = new ReactiveLoadBalancerClientFilter(
			clientFactory, properties);
	when(chain.filter(exchange)).thenReturn(Mono.empty());
	try {
		filter.filter(exchange, chain).block();
	}
	catch (NotFoundException exception) {
		assertThat(exception.getStatus()).isEqualTo(HttpStatus.NOT_FOUND);
	}
}
 
Example #4
Source File: GateWayExceptionHandlerAdvice.java    From SpringCloud with Apache License 2.0 6 votes vote down vote up
@ExceptionHandler(value = {Throwable.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result handle(Throwable throwable) {
    Result result = Result.fail();
    if (throwable instanceof ResponseStatusException) {
        result = handle((ResponseStatusException) throwable);
    } else if (throwable instanceof ConnectTimeoutException) {
        result = handle((ConnectTimeoutException) throwable);
    } else if (throwable instanceof NotFoundException) {
        result = handle((NotFoundException) throwable);
    } else if (throwable instanceof RuntimeException) {
        result = handle((RuntimeException) throwable);
    } else if (throwable instanceof Exception) {
        result = handle((Exception) throwable);
    }
    return result;
}
 
Example #5
Source File: ErrorExceptionHandler.java    From SpringBlade with Apache License 2.0 5 votes vote down vote up
/**
 * 获取异常属性
 */
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
	int code = 500;
	Throwable error = super.getError(request);
	if (error instanceof NotFoundException) {
		code = 404;
	}
	if (error instanceof ResponseStatusException) {
		code = ((ResponseStatusException) error).getStatus().value();
	}
	return ResponseProvider.response(code, this.buildMessage(request, error));
}
 
Example #6
Source File: JsonExceptionHandler.java    From MyShopPlus with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange serverWebExchange, Throwable throwable) {
    // 按照异常类型进行处理
    HttpStatus httpStatus;
    String body;
    if (throwable instanceof NotFoundException) {
        httpStatus = HttpStatus.NOT_FOUND;
        body = "Service Not Found";
    } else if (throwable instanceof ResponseStatusException) {
        ResponseStatusException responseStatusException = (ResponseStatusException) throwable;
        httpStatus = responseStatusException.getStatus();
        body = responseStatusException.getMessage();
    } else {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = "Internal Server Error";
    }

    // 封装响应结果
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);

    String msg = "{\"code\":" + httpStatus.value() + ",\"message\": \"" + body + "\"}";
    result.put("body", msg);

    // 错误日志
    ServerHttpRequest request = serverWebExchange.getRequest();
    log.error("[全局系统异常]\r\n请求路径:{}\r\n异常记录:{}", request.getPath(), throwable.getMessage());

    if (serverWebExchange.getResponse().isCommitted()) {
        return Mono.error(throwable);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(serverWebExchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(throwable))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(serverWebExchange, response));
}
 
Example #7
Source File: FebsGatewayExceptionHandler.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 异常处理,定义返回报文格式
 */
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
    Throwable error = super.getError(request);
    log.error(
            "请求发生异常,请求URI:{},请求方法:{},异常信息:{}",
            request.path(), request.methodName(), error.getMessage()
    );
    String errorMessage;
    if (error instanceof NotFoundException) {
        String serverId = StringUtils.substringAfterLast(error.getMessage(), "Unable to find instance for ");
        serverId = StringUtils.replace(serverId, "\"", StringUtils.EMPTY);
        errorMessage = String.format("无法找到%s服务", serverId);
    } else if (StringUtils.containsIgnoreCase(error.getMessage(), "connection refused")) {
        errorMessage = "目标服务拒绝连接";
    } else if (error instanceof TimeoutException) {
        errorMessage = "访问服务超时";
    } else if (error instanceof ResponseStatusException
            && StringUtils.containsIgnoreCase(error.getMessage(), HttpStatus.NOT_FOUND.toString())) {
        errorMessage = "未找到该资源";
    } else {
        errorMessage = "网关转发异常";
    }
    Map<String, Object> errorAttributes = new HashMap<>(3);
    errorAttributes.put("message", errorMessage);
    return errorAttributes;
}
 
Example #8
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test(expected = NotFoundException.class)
public void shouldThrowExceptionWhenNoServiceInstanceIsFound() {
	URI uri = UriComponentsBuilder.fromUriString("lb://myservice").build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, uri);

	filter.filter(exchange, chain).block();
}
 
Example #9
Source File: InMemoryRouteDefinitionRepository.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> delete(Mono<String> routeId) {
	return routeId.flatMap(id -> {
		if (routes.containsKey(id)) {
			routes.remove(id);
			return Mono.empty();
		}
		return Mono.defer(() -> Mono.error(
				new NotFoundException("RouteDefinition not found: " + routeId)));
	});
}
 
Example #10
Source File: ReactiveLoadBalancerClientFilter.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
private Mono<Response<ServiceInstance>> choose(ServerWebExchange exchange) {
	URI uri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
	ReactorLoadBalancer<ServiceInstance> loadBalancer = this.clientFactory
			.getInstance(uri.getHost(), ReactorLoadBalancer.class,
					ServiceInstance.class);
	if (loadBalancer == null) {
		throw new NotFoundException("No loadbalancer available for " + uri.getHost());
	}
	return loadBalancer.choose(createRequest());
}
 
Example #11
Source File: GatewayNoLoadBalancerClientAutoConfiguration.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("Duplicates")
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
	String schemePrefix = exchange.getAttribute(GATEWAY_SCHEME_PREFIX_ATTR);
	if (url == null
			|| (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) {
		return chain.filter(exchange);
	}

	throw NotFoundException.create(use404,
			"Unable to find instance for " + url.getHost());
}
 
Example #12
Source File: AbstractGatewayControllerEndpoint.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@DeleteMapping("/routes/{id}")
public Mono<ResponseEntity<Object>> delete(@PathVariable String id) {
	return this.routeDefinitionWriter.delete(Mono.just(id))
			.then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build())))
			.onErrorResume(t -> t instanceof NotFoundException,
					t -> Mono.just(ResponseEntity.notFound().build()));
}
 
Example #13
Source File: DynamicRouteService.java    From momo-cloud-permission with Apache License 2.0 5 votes vote down vote up
@Override
public Mono<Void> delete(Mono<String> routeId) {
    return routeId.flatMap(id -> {
        if (redisTemplate.opsForHash().hasKey(GATEWAY_ROUTES, id)) {
            redisTemplate.opsForHash().delete(GATEWAY_ROUTES, id);
            return Mono.empty();
        }
        return Mono.defer(() -> Mono.error(new NotFoundException("RouteDefinition not found: " + routeId)));
    });
}
 
Example #14
Source File: FwGatewayExceptionHandler.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 异常处理,定义返回报文格式
 */
@Override
protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
    Throwable error = super.getError(request);
    log.error(
            "请求发生异常,请求URI:{},请求方法:{},异常信息:{}",
            request.path(), request.methodName(), error.getMessage()
    );
    String errorMessage;
    if (error instanceof NotFoundException) {
        String serverId = StringUtils.substringAfterLast(error.getMessage(), "Unable to find instance for ");
        serverId = StringUtils.replace(serverId, "\"", StringUtils.EMPTY);
        errorMessage = String.format("无法找到%s服务", serverId);
    } else if (StringUtils.containsIgnoreCase(error.getMessage(), "connection refused")) {
        errorMessage = "目标服务拒绝连接";
    } else if (error instanceof TimeoutException) {
        errorMessage = "访问服务超时";
    } else if (error instanceof ResponseStatusException
            && StringUtils.containsIgnoreCase(error.getMessage(), HttpStatus.NOT_FOUND.toString())) {
        errorMessage = "未找到该资源";
    } else {
        errorMessage = "网关转发异常";
    }
    Map<String, Object> errorAttributes = new HashMap<>(2);
    errorAttributes.put("msg", errorMessage);
    errorAttributes.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
    return errorAttributes;
}
 
Example #15
Source File: JsonExceptionHandler.java    From open-cloud with MIT License 5 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    /**
     * 按照异常类型进行处理
     */
    ResultBody resultBody;
    ServerHttpRequest request = exchange.getRequest();
    if("/favicon.ico".equals(exchange.getRequest().getURI().getPath())){
        return Mono.empty();
    }
    if (ex instanceof NotFoundException) {
        resultBody = ResultBody.failed().code(ErrorCode.SERVICE_UNAVAILABLE.getCode()).msg(ErrorCode.SERVICE_UNAVAILABLE.getMessage()).httpStatus(HttpStatus.SERVICE_UNAVAILABLE.value()).path(request.getURI().getPath());
        log.error("==> 错误解析:{}", resultBody);
    } else {
        resultBody = OpenGlobalExceptionHandler.resolveException((Exception) ex, exchange.getRequest().getURI().getPath());
    }
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(resultBody);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> {
                return write(exchange, response,ex);
            });
}
 
Example #16
Source File: GateWayExceptionHandlerAdvice.java    From SpringCloud with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(value = {NotFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public Result handle(NotFoundException ex) {
    log.error("not found exception:{}", ex.getMessage());
    return Result.fail(SystemErrorType.GATEWAY_NOT_FOUND_SERVICE);
}
 
Example #17
Source File: GatewayExceptionHandler.java    From spring-microservice-exam with MIT License 4 votes vote down vote up
/**
   * 处理逻辑
   *
   * @param exchange exchange
   * @param ex       ex
   * @return Mono
   */
  @Override
  public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
      String msg = "Internal Server Error";
      // 返回给前端用的状态码
      int keyCode = ApiMsg.KEY_UNKNOWN;
      int msgCode = ApiMsg.ERROR;
      if (ex instanceof NotFoundException) {
      	// 服务不可用
	keyCode = ApiMsg.KEY_SERVICE;
	msgCode = ApiMsg.UNAVAILABLE;
      } else if (ex instanceof ResponseStatusException) {
          ResponseStatusException responseStatusException = (ResponseStatusException) ex;
          msg = responseStatusException.getMessage();
	// 服务响应错误
	keyCode = ApiMsg.KEY_SERVICE;
	msgCode = ApiMsg.ERROR;
      } else if (ex instanceof InvalidValidateCodeException) {
          msg = ex.getMessage();
          // 验证码错误
	keyCode = ApiMsg.KEY_VALIDATE_CODE;
} else if (ex instanceof ValidateCodeExpiredException) {
          msg = ex.getMessage();
          // 验证码过期
	keyCode = ApiMsg.KEY_VALIDATE_CODE;
	msgCode = ApiMsg.EXPIRED;
      } else if (ex instanceof InvalidAccessTokenException) {
          msg = ex.getMessage();
          // token非法
	keyCode = ApiMsg.KEY_TOKEN;
	msgCode = ApiMsg.INVALID;
      }
      // 封装响应体
      ResponseBean<String> responseBean = new ResponseBean<>(msg, keyCode, msgCode);
      // 错误记录
      ServerHttpRequest request = exchange.getRequest();
      log.error("GatewayExceptionHandler: {}, error: {}", request.getPath(), ex.getMessage());
      if (exchange.getResponse().isCommitted())
          return Mono.error(ex);
      exceptionHandlerResult.set(responseBean);
      ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
      return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
              .switchIfEmpty(Mono.error(ex))
              .flatMap((handler) -> handler.handle(newRequest))
              .flatMap((response) -> write(exchange, response));
  }
 
Example #18
Source File: ExceptionHandle.java    From microservice-recruit with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    /**
     * 按照异常类型进行处理
     */
    HttpStatus httpStatus;
    String body;
    if (ex instanceof MyException) {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(((MyException) ex).getCode(), ex.getMessage()));
    } else if (ex instanceof NotFoundException) {
        httpStatus = HttpStatus.NOT_FOUND;
        body = JSONObject.toJSONString(ResponseMessage.error(404, ex.getMessage()));
    } else if (ex instanceof ResponseStatusException) {
        ResponseStatusException responseStatusException = (ResponseStatusException) ex;
        httpStatus = responseStatusException.getStatus();
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    } else {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    }
    /**
     * 封装响应体,此body可修改为自己的jsonBody
     */
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);
    result.put("body", body);
    /**
     * 错误记录
     */
    ServerHttpRequest request = exchange.getRequest();
    log.error("[全局异常处理]异常请求路径:{},记录异常信息:{}", request.getPath().pathWithinApplication().value(), ex.getMessage());
    ex.printStackTrace();
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(exchange, response));

}
 
Example #19
Source File: GateWayExceptionHandlerAdvice.java    From JetfireCloud with Apache License 2.0 4 votes vote down vote up
@ExceptionHandler(value = {NotFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public Result handle(NotFoundException ex) {
    log.error("not found exception:{}", ex.getMessage());
    return Result.fail(ErrorType.GATEWAY_NOT_FOUND_SERVICE);
}
 
Example #20
Source File: ReactiveLoadBalancerClientFilter.java    From spring-cloud-gateway with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("Duplicates")
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
	String schemePrefix = exchange.getAttribute(GATEWAY_SCHEME_PREFIX_ATTR);
	if (url == null
			|| (!"lb".equals(url.getScheme()) && !"lb".equals(schemePrefix))) {
		return chain.filter(exchange);
	}
	// preserve the original url
	addOriginalRequestUrl(exchange, url);

	if (log.isTraceEnabled()) {
		log.trace(ReactiveLoadBalancerClientFilter.class.getSimpleName()
				+ " url before: " + url);
	}

	return choose(exchange).doOnNext(response -> {

		if (!response.hasServer()) {
			throw NotFoundException.create(properties.isUse404(),
					"Unable to find instance for " + url.getHost());
		}

		URI uri = exchange.getRequest().getURI();

		// if the `lb:<scheme>` mechanism was used, use `<scheme>` as the default,
		// if the loadbalancer doesn't provide one.
		String overrideScheme = null;
		if (schemePrefix != null) {
			overrideScheme = url.getScheme();
		}

		DelegatingServiceInstance serviceInstance = new DelegatingServiceInstance(
				response.getServer(), overrideScheme);

		URI requestUrl = reconstructURI(serviceInstance, uri);

		if (log.isTraceEnabled()) {
			log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
		}
		exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);
	}).then(chain.filter(exchange));
}
 
Example #21
Source File: ExceptionHandle.java    From microservice-recruit with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
    /**
     * 按照异常类型进行处理
     */
    HttpStatus httpStatus;
    String body;
    if (ex instanceof MyException) {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(((MyException) ex).getCode(), ex.getMessage()));
    } else if (ex instanceof NotFoundException) {
        httpStatus = HttpStatus.NOT_FOUND;
        body = JSONObject.toJSONString(ResponseMessage.error(404, ex.getMessage()));
    } else if (ex instanceof ResponseStatusException) {
        ResponseStatusException responseStatusException = (ResponseStatusException) ex;
        httpStatus = responseStatusException.getStatus();
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    } else {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        body = JSONObject.toJSONString(ResponseMessage.error(500, ex.getMessage()));
    }
    /**
     * 封装响应体,此body可修改为自己的jsonBody
     */
    Map<String, Object> result = new HashMap<>(2, 1);
    result.put("httpStatus", httpStatus);
    result.put("body", body);
    /**
     * 错误记录
     */
    ServerHttpRequest request = exchange.getRequest();
    log.error("[全局异常处理]异常请求路径:{},记录异常信息:{}", request.getPath().pathWithinApplication().value(), ex.getMessage());
    ex.printStackTrace();
    /**
     * 参考AbstractErrorWebExceptionHandler
     */
    if (exchange.getResponse().isCommitted()) {
        return Mono.error(ex);
    }
    exceptionHandlerResult.set(result);
    ServerRequest newRequest = ServerRequest.create(exchange, this.messageReaders);
    return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse).route(newRequest)
            .switchIfEmpty(Mono.error(ex))
            .flatMap((handler) -> handler.handle(newRequest))
            .flatMap((response) -> write(exchange, response));

}
 
Example #22
Source File: DynamicRouteService.java    From spring-microservice-exam with MIT License 2 votes vote down vote up
/**
 * 删除路由
 *
 * @param id id
 * @return Mono
 */
public Mono<ResponseEntity<Object>> delete(Long id) {
    return this.routeDefinitionWriter.delete(Mono.just(String.valueOf(id)))
            .then(Mono.defer(() -> Mono.just(ResponseEntity.ok().build())))
            .onErrorResume(t -> t instanceof NotFoundException, t -> Mono.just(ResponseEntity.notFound().build()));
}