package com.sf.vertx.handle;

import com.sf.vertx.utils.ProxyTool;

import io.vertx.core.http.HttpHeaders;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.HttpException;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class RestfulFailureHandlerImpl implements RestfulFailureHandler {

	@SuppressWarnings("unlikely-arg-type")
	@Override
	public void handle(RoutingContext frc) {
		Throwable failure = frc.failure();
		log.info("Throwable error:{}", failure);
		if (failure instanceof HttpException) {
			HttpException httpException = (HttpException) failure;
			// frc.response().setStatusCode(404).end();
			if(ProxyTool._ERROR.containsKey(httpException.getPayload())) {
				JsonObject dataJson = new JsonObject(httpException.getPayload());
				frc.response().setChunked(true).setStatusCode(httpException.getStatusCode())
						.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(dataJson.size()))
						.putHeader("Content-Type", "application/json").end(dataJson.toBuffer());
				return;
			}
		}
		frc.response().setChunked(true).setStatusCode(400).putHeader("Content-Type", "application/json")
		.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(ProxyTool.DEFAULT_ERROR_MSG.length()))
		.end(ProxyTool.DEFAULT_ERROR_MSG);
		return;
	}

}
