package gaf3.core.jpa.web

import gaf3.core.data.ErrorResult
import gaf3.core.exception.BusinessError
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.dao.DataAccessException
import org.springframework.http.HttpStatus
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestControllerAdvice
import javax.validation.ConstraintViolationException


@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
class GafJpaControllerAdvice {
    val log: Logger = LoggerFactory.getLogger(GafJpaControllerAdvice::class.java)

    @ExceptionHandler(DataAccessException::class)
    @ResponseBody
    fun handleError(ex: DataAccessException, res: ServerHttpResponse): ErrorResult {
        log.warn("DataAccessException: {}", ex.message)
        log.debug("handleError", ex)
        res.setStatusCode(HttpStatus.BAD_REQUEST)
        return ErrorResult(errcode = BusinessError.ERR_SERVICE_FAULT, errmsg = "数据库错误", details = ex.message)
    }
}