package com.rrtx.services.common.handler;

import cn.hutool.json.JSONUtil;
import com.rrtx.fap.core.entity.R;
import com.rrtx.fap.core.exception.base.BusinessException;
import com.rrtx.services.common.exception.BusinessCodeException;
import com.rrtx.services.common.utils.TranslateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * ClassName: GlobalExceptionHandler<br>
 * Description: GlobalExceptionHandler <br>
 * Company: rrtx
 *
 * @author rrtx
 * @version v1.0.0    2019/7/24 4:51 PM  xugz    文件初始创建
 */
@Slf4j
@RestControllerAdvice
@Order(value = Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public R handleException(Exception e) {
		log.error("系统内部异常，异常信息", e);
		R r =  R.code(HttpStatus.INTERNAL_SERVER_ERROR.value(), "System Err!");
		log.info("result for exception {}" , JSONUtil.toJsonStr(r));
		return r;
	}

	@ExceptionHandler(value = BusinessException.class)
	public R handleBusinessException(BusinessException e) {
		log.error("系统错误", e);
		R r = new R(e.getErrorCode(), e.getMessage());
		log.info("business exception {}", JSONUtil.toJsonStr(r));
		return r;
	}

	@ExceptionHandler(value = BusinessCodeException.class)
	public R handleBusinessException(BusinessCodeException e) {
		log.error("系统错误", e);
		String errorMsg = TranslateUtil.val4Err(e.getErrorCode());
		R r = new R(e.getErrorCode(), errorMsg);
		log.info("business code exception{}", JSONUtil.toJsonStr(r));
		return r;
	}

}