package com.tykj.workflowcore.base.result;

import com.fasterxml.jackson.databind.exc.InvalidFormatException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
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;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;


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


    /**
     * 业务错误
     *
     * @param e 报错信息
     */
    @ResponseBody
    @ExceptionHandler(ApiException.class)
    public ResponseEntity errorMessage(ApiException e) {
        log.warn("[自定义异常] {}", e.toString());
        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("字段长度错误，请修改为合适的长度！");
    }

}

