/**
 * $Id: RestControllerAdviceHandler.java 13331 2016-07-06 09:09:33Z anjiabin $
 * Copyright(C) 2014-2020 easegame, All Rights Reserved.
 */
package com.liquidnet.common.exception;

import com.alibaba.fastjson.JSON;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.common.exception.entity.Error;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;

/**
 * @author AnJiabin <jiabin.an@lightnet.io>
 * @version V1.0
 * @Description: TODO
 * @class: RestControllerAdviceHandler
 * @Package com.liquidnet.common.exception
 * @Copyright: LightNet @ Copyright (c) 2020
 * @date 2020/9/21 10:37
 */
@ControllerAdvice(annotations = RestController.class)
public class RestControllerAdviceHandler {
    private final Logger logger = LoggerFactory.getLogger(RestControllerAdviceHandler.class);

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity serviceExceptionHandler(Exception rex, WebRequest request) {
        logger.error("serviceExceptionHandler request : {} param:{}", request.getContextPath(), JSON.toJSONString(request.getParameterMap()));
        if ( rex instanceof LiquidnetFeignException) {
            LiquidnetFeignException ygex = ((LiquidnetFeignException) rex);
            String errorCode = ygex.errorCode().getCode();
            String message = ygex.getMessage();
            message = message == null ? ygex.errorCode().getMessage() : message;
            logger.error("LiquidnetServiceException errorCode:{} error : {}", errorCode, ygex.getMessage());
            return new ResponseEntity<Error>(new Error(errorCode,message), HttpStatus.EXPECTATION_FAILED);
        }
        if (rex instanceof LiquidnetServiceException) {
            LiquidnetServiceException ygex = ((LiquidnetServiceException) rex);
            String errorCode = ygex.errorCode().getCode();
            String message = ygex.getMessage();
            message = message == null ? ygex.errorCode().getMessage() : message;
            logger.error("LiquidnetServiceException errorCode:{} error : {}", errorCode, ygex.getMessage());
            return new ResponseEntity<Error>(new Error(errorCode,message), HttpStatus.EXPECTATION_FAILED);
        }else {
            logger.error("serviceExceptionHandler : {}", rex);
            return new ResponseEntity<Error>(new Error(ErrorCode.RESPONSE_ERROE_UNKNOWN.getCode(), ErrorCode.RESPONSE_ERROE_UNKNOWN.getMessage()), HttpStatus.EXPECTATION_FAILED);
        }
    }
}
