package digital.laboratory.platform.entrustment.config;

import digital.laboratory.platform.common.core.util.R;
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.servlet.NoHandlerFoundException;

import java.util.HashMap;
import java.util.Map;

/**
 * Spring Boot 自定义异常处理
 * 所有的异常都派生自 Exception, 如果我们定义了某个异常的处理 Handler, Spring Boot 会调用用对应的异常 Handler, 否则会调用 Exception Handler.
 * 有一个前提是在 application.yml 中定义两个属性, 让 springboot 在没有找到 url 的处理器触发异常; 让 springboot 不要自作多情加 /error 这个 map
 *   mvc:
 *     throw-exception-if-no-handler-found: true
 *   web:
 *     resources:
 *       add-mappings: false
 * 只有如此, springboot 才会触发异常。
 *
 */


@ControllerAdvice
public class ErrorController {

	@ExceptionHandler(Exception.class)
	@ResponseBody
	public ResponseEntity error(Exception ex) {
System.out.println("ErrorController.error Exception");
ex.printStackTrace();
		Map<String, Object> map = new HashMap<>();
		map.put("Exception", ex.getClass().getName());
		map.put("message", ex.getMessage());
		map.put("localizedMessage", ex.getLocalizedMessage());
		map.put("toString", ex.toString());

		return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(R.failed(map, "发生异常 "+ex.getMessage()));
	}


	@ExceptionHandler(value = {NoHandlerFoundException.class})
	@ResponseBody
	public ResponseEntity error(NoHandlerFoundException ex) {
//System.out.println("ErrorController.error NoHandlerFoundException");
//ex.printStackTrace();
//		//ex.getRawStatusCode()
		Map<String, Object> map = new HashMap<>();
		map.put("Exception", ex.getClass().getName());
		map.put("message", ex.getMessage());
		map.put("localizedMessage", ex.getLocalizedMessage());
		map.put("requestURL", ex.getRequestURL());
		map.put("httpMethod", ex.getHttpMethod());
//		map.put("cause", ex.getCause().toString());
		map.put("toString", ex.toString());
//		map.put("comments", "单独的 ExceptionHandler, 系统管理捕获的全局异常 NoHandlerFoundException");
//		//return map;
//		//ResponseEntity<Map<String,Object>> r = new ResponseEntity<Map<String,Object>>(map, HttpStatus.INTERNAL_SERVER_ERROR);
//		//ResponseEntity<Map<String,Object>> r = new ResponseEntity<Map<String,Object>>(map, HttpStatus.NOT_FOUND);
//		//return r;
//		return ResponseEntity.status(HttpStatus.NOT_FOUND).body(map);

		return ResponseEntity.status(HttpStatus.NOT_FOUND).body(R.failed(map, "没有找到"));
	}


}

