package com.css.simulation.resource.common.infra.config.advice;

import api.common.pojo.common.ResponseBodyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理
 *
 * @author martin
 */
@RestControllerAdvice
@Scope(value = ConfigurableBeanFactory.SCOPE_SINGLETON)
@Slf4j
public class AllExceptionHandlerAdvice {

    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseBodyVO<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    /**
     * 服务器错误异常统一处理
     */
    @ExceptionHandler(Exception.class)
    public ResponseBodyVO<Object> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, "服务器错误！");
    }

}
