package cn.com.qmth.stmms.api.controller;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;

import cn.com.qmth.stmms.api.utils.AuthInfoUtils;
import cn.com.qmth.stmms.biz.api.auth.exception.ApiException;
import cn.com.qmth.stmms.common.controller.BaseController;

public class BaseApiController extends BaseController {

    protected static final Logger log = LoggerFactory.getLogger(BaseApiController.class);

    @ExceptionHandler
    public void exception(HttpServletResponse response, Exception ex) {
        log.error("api execute error", ex);
        response.addHeader(AuthInfoUtils.ERROR_MESSAGE_HEADER_KEY, StringUtils.trimToEmpty(ex.getMessage()));
        try {
            if (ex instanceof ApiException) {
                ApiException e = (ApiException) ex;
                response.sendError(e.getCode());
            } else {
                response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        } catch (Exception e) {
            log.error("api response senderror", e);
        }
    }
}
