package org.wcs.serve.exception.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.wcs.factory.PubServeResponseFactory;
import org.wcs.model.vo.pub.PubServeResponse;

import java.util.List;

@Slf4j
@RestControllerAdvice(basePackages = {"org.wcs.serve.controller.pub"})
public class PubExceptionHandler {

    /**
     * 接口层参数校验失败
     * @param ex 异常信息
     * @return 响应结果
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public PubServeResponse handleException(MethodArgumentNotValidException ex) {
        log.info("外部接口，接口层参数校验失败", ex);
        List<ObjectError> allErrors = ex.getAllErrors();
        if(allErrors.isEmpty()) {
            return PubServeResponseFactory.fail("参数校验失败，请检查传入的数据格式");
        }
        return PubServeResponseFactory.fail(allErrors.getFirst().getDefaultMessage());
    }

    /**
     * 兜底异常
     * @param ex 异常信息
     * @return 响应结果
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public PubServeResponse handleException(Exception ex) {
        log.error("外部接口，系统异常", ex);
        return PubServeResponseFactory.fail("系统异常：" + ex.getMessage());
    }
}
