package com.css.simulation.resource.scene.common.exception;

import api.common.pojo.common.ResponseBodyVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.http.converter.HttpMessageNotReadableException;
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.Objects;

@ControllerAdvice
@Slf4j
@Scope("singleton")
public class GlobalExceptionHandler {
    /**
     * 方法参数校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    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(HttpMessageNotReadableException.class)
    @ResponseBody
    public ResponseBodyVO<Object> handleHttpMessageNotReadableException(Exception e) {
        log.error(e.getMessage(), e);
        return new ResponseBodyVO<>(ResponseBodyVO.Response.SERVER_FAILURE, "Required request body is missing！");
    }

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

}
