<gh_stars>0
package cn.fjc.base;

import cn.fjc.core.exception.BizException;
import cn.fjc.core.constants.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.common.errors.AuthorizationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

/**
 * 全局异常处理器
 * @author liuhaokun
 */
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BizException.class)
    public Result<Object> handleBusinessException(BizException bizException) {
        return Result.failed(Result.ERROR_BUSINESS, bizException.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result<Object> handlerNoFoundException(Exception exception) {
        log.error(exception.getMessage(), exception);
        return Result.failed(HttpStatus.NOT_FOUND.value(), "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result<Object> handleDuplicateKeyException(DuplicateKeyException duplicateKeyException) {
        log.error(duplicateKeyException.getMessage(), duplicateKeyException);
        return Result.failed(Result.ERROR_BUSINESS, "数据库中已存在该记录");
    }

    @ExceptionHandler(AuthorizationException.class)
    public Result<Object> handleAuthorizationException(AuthorizationException authorizationException) {
        log.error(authorizationException.getMessage(), authorizationException);
        return Result.failed(Result.NOT_PERMISSION, "没有权限，请联系管理员授权");
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception exception) {
        log.error(exception.getMessage(), exception);
        return Result.failed(Result.ERROR_BUSINESS, exception.getMessage());
    }

}
