package com.sckw.usual.handle;

import com.sckw.core.web.response.HttpResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
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 org.springframework.web.bind.annotation.ResponseStatus;


/**
 * 全局异常处理器，处理各种异常，并返回统一的 HTTP 结果
 */
@ControllerAdvice
public class AllExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(AllExceptionHandler.class);

    /**
     * 处理通用异常
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public HttpResult handleGeneralException(Exception exception) {
        logger.error(exception.getMessage(), exception);
        HttpResult result = new HttpResult();
        result.setCode(500);
        result.setMsg(exception.getMessage());
        return result;
    }

    /**
     * 处理方法参数校验异常
     */
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public HttpResult handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        logger.error(exception.getMessage(), exception);
        HttpResult result = new HttpResult();
        result.setCode(500);
        result.setMsg(exception.getBindingResult().getFieldError().getDefaultMessage());
        return result;
    }
}
