package thyyxxk.webserver.config.exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
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 thyyxxk.webserver.entity.ResultVo;
import thyyxxk.webserver.utils.ResultVoUtil;

import java.util.Objects;

/**
 * @author dj
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final String DATABASE = "database";
    private static final String JSON_PARSE = "JSON parse error";

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResultVo<String> bindException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        return ResultVoUtil.fail(ExceptionEnum.NULL_POINTER, Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResultVo<String> bizExceptionHandler(BizException e) {
        log.error("【BizException】发生业务异常", e);
        return new ResultVo<>(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultVo<String> exceptionHandler(NullPointerException e) {
        log.error("【NullPointerException】发生空指针异常", e);
        return ResultVoUtil.fail(ExceptionEnum.NULL_POINTER, "错误原因：" + e.getCause().getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVo<String> exceptionHandler(Exception e) {
        String message = e.getCause().getMessage();
        log.error("【Exception】发生异常", e);
        if (message.contains(DATABASE)) {
            message = "数据库执行出错，请联系信息中心处理。错误原因：" + e.getCause().getMessage();
        } else if (message.contains(JSON_PARSE)) {
            message = "JSON转换发生异常，请检查参数。错误原因：" + e.getCause().getMessage();
        }
        return ResultVoUtil.fail(ExceptionEnum.INTERNAL_SERVER_ERROR, message);
    }
}
