package com.xjrsoft.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.xjrsoft.common.enums.ResponseCode;
import com.xjrsoft.common.model.result.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Author: tzx
 * @Date: 2022/3/3 15:38
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 全局异常处理
     *
     * @Author: tzx
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R globalExceptionHandler(Exception e){
        log.error(e.getMessage(), e);
        return R.error(ResponseCode.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
    }


    /**
     * 未登录异常处理
     *
     * @Author: tzx
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public R notLoginExceptionHandler(NotLoginException e){
        log.error(e.getMessage(), e);
        return R.error(ResponseCode.UN_AUTHORIZED.getCode(),ResponseCode.UN_AUTHORIZED.getMessage());
    }

    /**
     * 权限异常
     *
     * @Author: tzx
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseBody
    public R notPermissionExceptionHandler(NotPermissionException e){
        log.error(e.getMessage(), e);
        return R.error(ResponseCode.UN_AUTHORIZED.getCode(),e.getMessage());
    }

    /**
     * 参数错误异常
     *
     * @Author: tzx
     */
    @ResponseBody
    @ExceptionHandler({BindException.class})
    public R paramExceptionHandler(BindException e) {
        log.error(e.getMessage(), e);
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息，如果存在就使用异常中的消息，否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数，按正常逻辑，只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return R.error(fieldError.getDefaultMessage());
            }
        }
        return R.error("请求参数错误");
    }

}
