package com.keao.edu.zuul.web.controller;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ErrorHandlerController implements ErrorController {

	@Override
	public String getErrorPath() {
		return "/error";
	}

	@RequestMapping("/error")
	@ResponseBody
	public Object error() {
		RequestContext ctx = RequestContext.getCurrentContext();
		ZuulException exception = (ZuulException) ctx.getThrowable();
		
		Throwable e = ExceptionUtils.getRootCause(exception);
		if (e == null) {
			e = exception;
		}

		HttpResponseResult result = new HttpResponseResult();
		result.setCode(exception.nStatusCode);
		result.setMsg(e.getMessage());
		result.setStatus(false);

		return result;
	}

	class HttpResponseResult {

		public final static int TIME_OUT = -1;

		private boolean status = true;
		private String msg;
		private Object data;
		private int code;

		public HttpResponseResult(boolean status, int code, Object data, String message) {
			this.status = status;
			this.msg = message;
			this.data = data;
			this.code = code;
		}

		public HttpResponseResult() {
		}

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		public boolean getStatus() {
			return status;
		}

		public void setStatus(boolean status) {
			this.status = status;
		}

		public String getMsg() {
			return msg;
		}

		public void setMsg(String msg) {
			this.msg = msg;
		}

		public Object getData() {
			return data;
		}

		public void setData(Object data) {
			this.data = data;
		}

		public void success() {
			this.status = true;
		}

		public void fail() {
			this.status = false;
		}

	}
}
