package com.tykj.base.result;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import com.tykj.base.result.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLSyntaxErrorException;


/**
 * 错误处理类
 * 所有的报错信息都会通过本层的方法向外界返回
 *
 * @author HuangXiahao
 **/

@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    /**
     * 业务错误
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(ApiException.class)
    public ResponseEntity errorMessage(ApiException e) {
        log.warn("[自定义异常] {}", e.toString());
        e.printStackTrace();
        if (e.getResponseEntity() != null) {
            return e.getResponseEntity();
        }
        return ResultUtil.failed(e.getMessage());
    }


    /**
     * 处理字段长度异常
     * @param invalidFormatException
     * @return
     */
    @ExceptionHandler(InvalidFormatException.class)
    public ResponseEntity handle(InvalidFormatException invalidFormatException){
        log.warn(invalidFormatException.toString());
        return ResultUtil.failed("字段长度错误，请修改为合适的长度！");
    }



    @ExceptionHandler(SQLSyntaxErrorException.class)
    public ResponseEntity handleSQl(InvalidFormatException invalidFormatException){
        log.warn(invalidFormatException.toString());
        return ResultUtil.failed("列名不合法，请修改列名！");
    }
}

