package cn.pluss.platform.controller.common;

import cn.pluss.platform.exception.MsgException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * @author djh
 * 定义一些异常的httpStatus
 */
@Slf4j
@RequestMapping("/error")
@RestController
public class CustomErrorController extends BasicErrorController {

    public CustomErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);

        if (Objects.equals(status, HttpStatus.NOT_FOUND)) {
            // 这里抛出异常让全局异常处理器去处理
            throw new MsgException("请稍后重试");
        }

        log.error("未知错误：{}", status.toString());
        throw new MsgException("未知错误");
    }

    @Override
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        throw new MsgException("请稍后重试");
    }
}
