package com.uas.account.web.advice;

import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.uas.account.exception.VisibleError;

@ControllerAdvice
public class ExceptionHandlerAdvice {

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

	private ModelMap error(String errMsg) {
		return new ModelMap("error", true).addAttribute("errMsg", errMsg);
	}

	/**
	 * 处理运行时抛出异常
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(RuntimeException.class)
	public ResponseEntity<ModelMap> handleRuntimeException(RuntimeException ex) {
		logger.error("RuntimeException", ex);
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json; charset=utf-8");
		return new ResponseEntity<ModelMap>(error("出现异常"), headers, HttpStatus.OK);
	}

	/**
	 * 允许用户看见的异常信息，直接传递给客户端
	 * 
	 * @param ex
	 * @return
	 */
	@ExceptionHandler(VisibleError.class)
	public ResponseEntity<ModelMap> handleVisibleError(VisibleError ex) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json; charset=utf-8");
		return new ResponseEntity<ModelMap>(error(ex.getMessage()), headers, HttpStatus.OK);
	}

}
