package com.dxhy.common.handler;

import com.dxhy.common.constant.CommonConstants;
import com.dxhy.common.exception.BaseException;
import com.dxhy.common.exception.auth.ClientTokenException;
import com.dxhy.common.exception.auth.UserInvalidException;
import com.dxhy.common.exception.auth.UserTokenException;
import com.dxhy.common.msg.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @author jiaohongyang
 * @date 2019年3月26日 下午5:58:02
 *
 */
@ControllerAdvice("com.dxhy")
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(ClientTokenException.class)
    public BaseResponse clientTokenExceptionHandler(HttpServletResponse response, ClientTokenException ex) {
        response.setStatus(403);
        log.error(ex.getMessage(), ex);
        return new BaseResponse(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(UserTokenException.class)
    public BaseResponse userTokenExceptionHandler(HttpServletResponse response, UserTokenException ex) {
        response.setStatus(200);
        log.error(ex.getMessage(), ex);
        return new BaseResponse(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(UserInvalidException.class)
    public BaseResponse userInvalidExceptionHandler(HttpServletResponse response, UserInvalidException ex) {
        response.setStatus(200);
        log.error(ex.getMessage(), ex);
        return new BaseResponse(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public BaseResponse baseExceptionHandler(HttpServletResponse response, BaseException ex) {
        log.error(ex.getMessage(), ex);
        response.setStatus(500);
        return new BaseResponse(ex.getCode(), ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public BaseResponse otherExceptionHandler(HttpServletResponse response, Exception ex) {
        response.setStatus(500);

        if(!"Comparison method violates its general contract!".equals(ex.getMessage())){
            log.error(ex.getMessage(), ex);
        }
        return new BaseResponse(CommonConstants.EX_OTHER_CODE, ex.getMessage());
    }

}
