package com.ctrip.framework.apollo.common.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.ctrip.framework.apollo.common.exception.AbstractApolloHttpException;
import com.ctrip.framework.apollo.tracer.Tracer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.HttpMediaTypeException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.HttpStatusCodeException;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.FORBIDDEN;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.MediaType.APPLICATION_JSON;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {
  private Gson gson = new Gson();
  private static Type mapType = new TypeToken<Map<String, Object>>() {
  }.getType();

  private static final Logger logger = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);

  //处理系统内置的Exception
  @ExceptionHandler(Throwable.class)
  public ResponseEntity<Map<String, Object>> exception(HttpServletRequest request, Throwable ex) {
    return handleError(request, INTERNAL_SERVER_ERROR, ex);
  }

  @ExceptionHandler({HttpRequestMethodNotSupportedException.class, HttpMediaTypeException.class})
  public ResponseEntity<Map<String, Object>> badRequest(HttpServletRequest request,
                                                        ServletException ex) {
    return handleError(request, BAD_REQUEST, ex);
  }

  @ExceptionHandler(HttpStatusCodeException.class)
  public ResponseEntity<Map<String, Object>> restTemplateException(HttpServletRequest request,
                                                                   HttpStatusCodeException ex) {
    return handleError(request, ex.getStatusCode(), ex);
  }

  @ExceptionHandler(AccessDeniedException.class)
  public ResponseEntity<Map<String, Object>> accessDeny(HttpServletRequest request,
                                                        AccessDeniedException ex) {
    return handleError(request, FORBIDDEN, ex);
  }

  //处理自定义Exception
  @ExceptionHandler({AbstractApolloHttpException.class})
  public ResponseEntity<Map<String, Object>> badRequest(HttpServletRequest request, AbstractApolloHttpException ex) {
    return handleError(request, ex);
  }


  private ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request,
                                                          AbstractApolloHttpException ex) {
    return handleError(request, ex.getHttpStatus(), ex);
  }


  private ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request,
                                                          HttpStatus status, Throwable ex) {
    String message = ex.getMessage();

    logger.error(message, ex);
    Tracer.logError(ex);


    Map<String, Object> errorAttributes = new HashMap<>();
    boolean errorHandled = false;

    if (ex instanceof HttpStatusCodeException) {
      try {
        //try to extract the original error info if it is thrown from apollo programs, e.g. admin service
        errorAttributes = gson.fromJson(((HttpStatusCodeException) ex).getResponseBodyAsString(), mapType);
        status = ((HttpStatusCodeException) ex).getStatusCode();
        errorHandled = true;
      } catch (Throwable th) {
        //ignore
      }
    }

    if (!errorHandled) {
      errorAttributes.put("status", status.value());
      errorAttributes.put("message", message);
      errorAttributes.put("timestamp",
          LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
      errorAttributes.put("exception", ex.getClass().getName());

    }

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(APPLICATION_JSON);
    return new ResponseEntity<>(errorAttributes, headers, status);
  }

}

@@ -307,16 +307,46 @@
 actory;%0A
+import org.slf4j.event.Level;%0A
 import o
@@ -2178,24 +2178,36 @@
 _REQUEST, ex
+, Level.WARN
 );%0A  %7D%0A%0A  @E
@@ -3001,32 +3001,65 @@
 (request, ex
+.getHttpStatus(), ex, Level.ERROR
 );%0A  %7D%0A%0A
 %0A  private R
@@ -3038,32 +3038,34 @@
 el.ERROR);%0A  %7D%0A%0A
+  
 %0A  private Respo
@@ -3197,35 +3197,36 @@
     
-AbstractApolloHttpException
+HttpStatus status, Throwable
  ex)
@@ -3264,38 +3264,39 @@
 st, 
-ex.getHttpS
+s
 tatus
-()
 , ex
+, Level.ERROR
 );%0A  %7D%0A%0A
 %0A  p
@@ -3291,17 +3291,16 @@
 );%0A  %7D%0A%0A
-%0A
   privat
@@ -3458,32 +3458,48 @@
 us, Throwable ex
+, Level logLevel
 ) %7B%0A    String m
@@ -3528,67 +3528,46 @@
 ();%0A
-%0A
     
-logger.error(message, ex);%0A    Tracer.logError(ex
+printLog(message, ex, logLevel
 );%0A%0A
-%0A
     
@@ -4566,10 +4566,559 @@
 );%0A  %7D%0A%0A
+  //%E6%89%93%E5%8D%B0%E6%97%A5%E5%BF%97, %E5%85%B6%E4%B8%ADlogLevel%E4%B8%BA%E6%97%A5%E5%BF%97%E7%BA%A7%E5%88%AB: ERROR/WARN/DEBUG/INFO/TRACE%0A  private void printLog(String message, Throwable ex, Level logLevel) %7B%0A    switch (logLevel.toString()) %7B%0A      case %22ERROR%22:%0A        logger.error(message, ex);%0A        break;%0A      case %22WARN%22:%0A        logger.warn(message, ex);%0A        break;%0A      case %22DEBUG%22:%0A        logger.debug(message, ex);%0A        break;%0A      case %22INFO%22:%0A        logger.info(message, ex);%0A        break;%0A      case %22TRACE%22:%0A        logger.trace(message, ex);%0A        break;%0A    %7D%0A    %0A    Tracer.logError(ex);%0A  %7D%0A%0A
 %7D%0A

更改非法请求的log级别从ERROR到Warn https://github.com/ctripcorp/apollo/issues/1209