package com.community.huiju.exception;

import com.community.commom.constant.Constant;
import com.community.commom.mode.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 java.util.List;

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


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


    @ExceptionHandler(WisdomException.class)
    public ResponseBean handleException(WisdomException 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;
    }


}
