package com.chinaweal.aiccs.config;


import com.chinaweal.youfool.framework.springboot.exception.ExceptionHandlerAdvice;
import com.chinaweal.youfool.framework.springboot.log.filter.RestLogFilter;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Primary;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
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 javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author lwd
 * @since 2021/8/18 10:34
 **/

@ControllerAdvice
@Primary
@Slf4j
public class GlobalExceptionHandler {

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public RestResult<?> dataAccessExceptionHandler(Exception ex, HttpServletRequest request) {
        ExceptionHandlerAdvice.ErrorBody errorBody = new ExceptionHandlerAdvice.ErrorBody(MDC.get(RestLogFilter.UNIQUE_ID), ex.getClass().getCanonicalName(), null);
        request.setAttribute("ex", ex.getMessage());
        log.error("数据库读写异常", ex);
        return RestResult.error(ResultCode.DATA_ACCESS_EXCEPTION, errorBody);
    }

}

