package com.tofly.dispatch.common;

import com.tofly.common.core.entity.ResultRespone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
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;

/**
 * @author HaiQiu
 * @date 2021/11/19
 * 全局异常处理器
 */
@ControllerAdvice
@Order(1)
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public ResultRespone exception(Exception e) {
//        e.printStackTrace();
        LOGGER.debug(e.getMessage());
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            String errMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
            return ResultRespone.failed(errMsg);
        }
        if (e instanceof BindException){
            BindException ex = (BindException) e;
            String errMsg = ex.getBindingResult().getFieldError().getDefaultMessage();
            return ResultRespone.failed(errMsg);
        }
        return ResultRespone.failed(e.getMessage());
    }
}
