package com.huiju.estateagents.exception;

import com.huiju.estateagents.base.ResponseBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
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.multipart.MaxUploadSizeExceededException;

import java.util.List;

/**
 * 统一异常出口
 * @author weiximei
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionHandleAdice {


    @ExceptionHandler(Exception.class)
    public ResponseBean handleException(Exception e){
        e.printStackTrace();
        log.error(e.getMessage(),e);
        ResponseBean response = new ResponseBean();
        response.addError("系统异常,请稍后重试!");
        return response;
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseBean handleException(RuntimeException e){
        log.error(e.getMessage(),e);
        ResponseBean response = new ResponseBean();
        response.addError(e.getMessage());
        return response;
    }


    @ExceptionHandler(EstaException.class)
    public ResponseBean handleException(EstaException e) {
        log.error(e.getMessage(),e);
        ResponseBean response = new ResponseBean();
        response.addError(e.getMessage());
        return response;
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseBean handlelllewgalParamException(MethodArgumentNotValidException e){
        ResponseBean response = new ResponseBean();

        List<ObjectError> errors  =e.getBindingResult().getAllErrors();
        String message = "参数不合法";
        if (errors.size() >0) {
            message = errors.get(0).getDefaultMessage();
        }

        response.addError(message);

        return response;
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseBean handleException(MaxUploadSizeExceededException e){
        e.printStackTrace();
        log.error(e.getMessage(),e);
        ResponseBean response = new ResponseBean();
        response.addError("图片超过上传限制大小，请上传10MB以内的图片!");
        return response;
    }


}
