package cn.reghao.oss.console.config.web;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 处理 controller 返回的错误
 *
 * @author reghao
 * @date 2020-06-19 13:34:19
 */
@Api(tags = "controller 错误处理接口")
@Slf4j
@Controller
public class ControllerErrorHandler implements ErrorController {
    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping("/error")
    public String handleError(Model model, HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        log.error("http status code: " + statusCode);
        if (statusCode == 404) {
            model.addAttribute("statusCode", statusCode);
            model.addAttribute("msg", "页面去火星啦～");
        } else if (statusCode == 400) {
            model.addAttribute("statusCode", statusCode);
            model.addAttribute("msg", "参数错误");
        } else if (statusCode == 500) {
            model.addAttribute("statusCode", statusCode);
            model.addAttribute("msg", "服务器内部错误");
        } else {
            model.addAttribute("statusCode", statusCode);
            model.addAttribute("msg", "未知错误");
        }

        return "/404";
    }
}
