package com.tzy.framework.web.exception;

import com.tzy.common.dto.OutDTO;
import com.tzy.common.exception.ServiceException;
import com.tzy.common.utils.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Locale;

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

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

	@ExceptionHandler(ServiceException.class)
	public OutDTO serviceErr(ServiceException e) {
		log.info("运行时提示,访问地址:{},提示:", ServletUtils.getRequest().getRequestURI(), e);
		OutDTO error = OutDTO.error(e.getCode(), e.getMessage());
		error.setData(e.getData());
		return error;
	}

	/**
	 * 系统异常
	 */
	@ExceptionHandler(Exception.class)
	public OutDTO handleException(Exception e) {
		log.error("系统异常,访问地址:{},异常信息:", ServletUtils.getRequest().getRequestURI(), e);
		return OutDTO.error500("系统异常，请联系客服");
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	public OutDTO handleMethodArgumentNotValidException(MethodArgumentNotValidException e, Locale locale) {
		String defaultMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
		return OutDTO.error500(defaultMessage);
	}
}
