package com.philisense.www.exception;

import com.philisense.www.constant.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 *
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public final String  DATASUCCESS = "success";
    public final String  DATASTATUS = "status";
    public final String  DATAMESSAGE = "message";

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Map<String, Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                                   HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        result.put(DATASUCCESS, false);
        result.put(DATASTATUS, HttpStatus.BAD_METHOD);
        result.put(DATAMESSAGE, e.getMessage());
        return result;
    }

    /**
     * 服务异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler({ServiceException.class})
    public Map<String, Object> handleServiceException(ServiceException e, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',系统异常'{}'", requestURI, e.getMessage());
        result.put(DATASUCCESS, false);
        result.put(DATAMESSAGE, e.getMessage());
        return result;
    }

    /**
     * 系统异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler({Exception.class})
    public Map<String, Object> handleOtherException(Exception e, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',系统异常'{}'", requestURI, e.getMessage());
        result.put(DATASUCCESS, false);
        result.put(DATASTATUS, HttpStatus.ERROR);
        result.put(DATAMESSAGE, "系统发生未知异常");
        return result;
    }

}
