Java Code Examples for io.vertx.ext.web.Route#failureHandler()

The following examples show how to use io.vertx.ext.web.Route#failureHandler() . 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: VxApiApplication.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 初始化异常Handler
 * 
 * @param api
 * @param route
 */
public void initExceptionHanlder(VxApis api, Route route) {
	route.path(api.getPath());
	if (api.getMethod() != HttpMethodEnum.ALL) {
		route.method(HttpMethod.valueOf(api.getMethod().getVal()));
	}
	if (api.getConsumes() != null) {
		api.getConsumes().forEach(va -> route.consumes(va));
	}
	route.failureHandler(rct -> {
		rct.response().putHeader(SERVER, VxApiGatewayAttribute.FULL_NAME).putHeader(CONTENT_TYPE, api.getContentType())
				.setStatusCode(api.getResult().getFailureStatus()).end(api.getResult().getFailureExample());
		VxApiTrackInfos infos = new VxApiTrackInfos(appName, api.getApiName());
		if (rct.failure() != null) {
			infos.setErrMsg(rct.failure().getMessage());
			infos.setErrStackTrace(rct.failure().getStackTrace());
		} else {
			infos.setErrMsg("没有进一步信息 failure 为 null");
		}
		vertx.eventBus().send(thisVertxName + VxApiEventBusAddressConstant.SYSTEM_PLUS_ERROR, infos.toJson());
	});
}
 
Example 2
Source File: HttpServiceBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates the router for handling requests.
 * <p>
 * This method creates a router instance along with a route matching all request. That route is initialized with the
 * following handlers and failure handlers:
 * <ul>
 * <li>a handler and failure handler that creates tracing data for all server requests,</li>
 * <li>a default failure handler,</li>
 * <li>a handler limiting the body size of requests to the maximum payload size set in the <em>config</em>
 * properties.</li>
 * </ul>
 *
 * @return The newly created router (never {@code null}).
 */
protected Router createRouter() {

    final Router router = Router.router(vertx);
    final Route matchAllRoute = router.route();
    // the handlers and failure handlers are added here in a specific order!
    // 1. tracing handler
    final TracingHandler tracingHandler = createTracingHandler();
    matchAllRoute.handler(tracingHandler).failureHandler(tracingHandler);
    // 2. default handler for failed routes
    matchAllRoute.failureHandler(new DefaultFailureHandler());
    // 3. BodyHandler with request size limit
    log.info("limiting size of inbound request body to {} bytes", getConfig().getMaxPayloadSize());
    matchAllRoute.handler(BodyHandler.create().setUploadsDirectory(DEFAULT_UPLOADS_DIRECTORY)
            .setBodyLimit(getConfig().getMaxPayloadSize()));
    //4. AuthHandler
    addAuthHandler(router);
    return router;
}
 
Example 3
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public void addRoute(RuntimeValue<Router> router, Function<Router, Route> route, Handler<RoutingContext> handler,
        HandlerType blocking) {

    Route vr = route.apply(router.getValue());

    Handler<RoutingContext> requestHandler = handler;
    if (blocking == HandlerType.BLOCKING) {
        vr.blockingHandler(requestHandler, false);
    } else if (blocking == HandlerType.FAILURE) {
        vr.failureHandler(requestHandler);
    } else {
        vr.handler(requestHandler);
    }
}
 
Example 4
Source File: TestDefaultEdgeDispatcher.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testOnRequest(@Mocked Router router, @Mocked Route route
    , @Mocked RoutingContext context
    , @Mocked HttpServerRequest requst
    , @Mocked EdgeInvocation invocation) {
  DefaultEdgeDispatcher dispatcher = new DefaultEdgeDispatcher();
  Map<String, String> pathParams = new HashMap<>();
  pathParams.put("param0", "testService");
  pathParams.put("param1", "v1");

  new Expectations() {
    {
      router.routeWithRegex("/api/([^\\\\/]+)/([^\\\\/]+)/(.*)");
      result = route;
      route.handler((Handler<RoutingContext>) any);
      result = route;
      route.failureHandler((Handler<RoutingContext>) any);
      result = route;
      context.pathParams();
      result = pathParams;
      context.request();
      result = requst;
      requst.path();
      result = "/api/testService/v1/hello";
      invocation.setVersionRule("1.0.0.0-2.0.0.0");
      invocation.init("testService", context, "/testService/v1/hello",
          Deencapsulation.getField(dispatcher, "httpServerFilters"));
      invocation.edgeInvoke();
    }
  };
  dispatcher.init(router);
  Assert.assertEquals(dispatcher.enabled(), false);
  Assert.assertEquals(Utils.findActualPath("/api/test", 1), "/test");
  Assert.assertEquals(dispatcher.getOrder(), 20000);

  dispatcher.onRequest(context);
  // assert done in expectations.
}
 
Example 5
Source File: AbstractVertxBasedHttpProtocolAdapter.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates the router for handling requests.
 * <p>
 * This method creates a router instance along with a route matching all request. That route is initialized with the
 * following handlers and failure handlers:
 * <ol>
 * <li>a handler to add a Micrometer {@code Timer.Sample} to the routing context,</li>
 * <li>a handler and failure handler that creates tracing data for all server requests,</li>
 * <li>a handler to log when the connection is closed prematurely,</li>
 * <li>a default failure handler,</li>
 * <li>a handler limiting the body size of requests to the maximum payload size set in the <em>config</em>
 * properties,</li>
 * <li>(optional) a handler that applies the trace sampling priority configured for the tenant/auth-id of a
 * request.</li>
 * </ol>
 *
 * @return The newly created router (never {@code null}).
 */
protected Router createRouter() {

    final Router router = Router.router(vertx);
    final Route matchAllRoute = router.route();
    // the handlers and failure handlers are added here in a specific order!
    // 1. handler to start the metrics timer
    matchAllRoute.handler(ctx -> {
        ctx.put(KEY_MICROMETER_SAMPLE, getMetrics().startTimer());
        ctx.next();
    });
    // 2. tracing handler
    final TracingHandler tracingHandler = createTracingHandler();
    matchAllRoute.handler(tracingHandler).failureHandler(tracingHandler);

    // 3. handler to log when the connection is closed prematurely
    matchAllRoute.handler(ctx -> {
        if (!ctx.response().closed() && !ctx.response().ended()) {
            ctx.response().closeHandler(v -> logResponseGettingClosedPrematurely(ctx));
        }
        ctx.next();
    });

    // 4. default handler for failed routes
    matchAllRoute.failureHandler(new DefaultFailureHandler());

    // 5. BodyHandler with request size limit
    log.info("limiting size of inbound request body to {} bytes", getConfig().getMaxPayloadSize());
    final BodyHandler bodyHandler = BodyHandler.create(DEFAULT_UPLOADS_DIRECTORY)
            .setBodyLimit(getConfig().getMaxPayloadSize());
    matchAllRoute.handler(bodyHandler);

    // 6. handler to set the trace sampling priority
    Optional.ofNullable(getTenantTraceSamplingHandler())
            .ifPresent(tenantTraceSamplingHandler -> matchAllRoute.handler(tenantTraceSamplingHandler));
    return router;
}