package com.xydl.cac.exception;

import com.xydl.cac.model.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.NestedExceptionUtils;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        String message = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(","));
        return Response.fail(message);
    }

    @ExceptionHandler(HttpMessageConversionException.class)
    public Response<String> handleHttpMessageConversionException(HttpMessageConversionException ex) {
        String message = "类型转换异常：" + ex.getRootCause().getLocalizedMessage();
        return Response.fail(message);
    }

    @ExceptionHandler(BusinessException.class)
    public Response<String> handleBusinessException(BusinessException ex) {
        String message = ex.getMessage();
        log.error(message);
        return Response.fail(message);
    }

    @ExceptionHandler(Exception.class)
    public Response<String> handleException(Exception ex) {
        log.error("", ex);
        String message = ex.getMessage();
        return Response.fail(message);
    }
}